Know the smallest number with Function min()

Asked

Viewed 70 times

0

I want to know the smallest number of this list, which I present below the code.

I don’t know where I’m going wrong, I think I need to convert the list.

Example:

lista=[1, 3, 5]
def min(values):
    smallest = None
    for value in values:
        if smallest is None or values < smallest:
           smallest = value
    return smallest

menorvalor=min(lista)

The mistake you make is this

Typeerror: '<' not supported between instances of 'list' and 'int'

  • 1

    correct value < smallest

  • values < smallest - shouldn’t be value < smallest? (value in the singular instead of values plural)

1 answer

5

The problem is you’re comparing the list values and not the individual value value.

Wrong:

if smallest is None or values < smallest:
#                           ^^^ Essa é sua lista, e não o valor iterado

Corrected:

if smallest is None or value < smallest:
#                          ^ Aqui estamos comparando um por um


Staying:

lista=[1, 3, 5]
def min(values):
    smallest = None
    for value in values:
        if smallest is None or value < smallest:
           smallest = value
    return smallest

menorvalor=min(lista)

See working on IDEONE, with a more "shuffled" list to highlight the test.


To better understand

The line for value in values: "says" more or less like this:"For each item in values, execute the indented code below, with the item in the variable value each iteration (each execution)"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.