Does the function not return the minimum value?

Asked

Viewed 171 times

3

Make a Python function call min_max(t), which receives a list of numbers, and returns another list containing respectively the lowest and highest value of the original list.

Follow the code so far:

def min_max(t):

    x = max(t)
    y = min(t)
    return  x,y
    
t = input("Digite sua lista: ")
print(min_max(t))

But, the function is not catching the min, what must be the problem?

  • min_max = lambda t: [min(t),max(t)]

3 answers

11

In fact the problem is not in its function but in how the list of numbers is being passed to it:

t = input("Digite sua lista: ")
print(min_max(t))

This is sending a string and not a list, so your code should contain a conversion before:

def min_max(numeros): 
    return [max(numeros), min(numeros)]


if __name__ == "__main__":

    entrada = input("Digite sua lista: ")
    lista = [int(i) for i in entrada.split(",")]

    maior, menor = min_max(lista)

    print(maior, menor)

Of course, this conversion of mine is not perfect since it does not consider the existence of characters, fractional numbers and other things. One way to make it a little more robust would be to use the method isnumeric():

lista = [int(i) for i in entrada.split(",") if i.isnumeric()]

But in this case only integers larger than zero would be accepted.

8

The main problem is that you are passing a string as a parameter of your function:

t = input("Digite sua lista: ")
print(min_max(t))

The return of function input is always a string. When you call the functions min and max in a string, you get the minimum and maximum values according to the alphabetical order:

min('spam') = 'a'
max('spam') = 's'

As you need to deal with numerical values, you will need to treat your input. If you are typing the values separated by a blank space, you will need to split the string into spaces and convert each value to a number:

entrada = input("Digite sua lista: ")
numeros = [int(numero) for numero in entrada.split()]

print(min_max(numeros))

So for an entrance 3 6 1 5 the exit will be (6, 1), because notice that is returning the largest and the smallest number respectively.

7

As already said the problem is not in the function min_max() and yes in the way it gets its input.

If the purpose of the program is for the user to enter a syntactically valid python list it is possible to use the function ast.literal_eval() to parse the input. This function securely evaluates an expression or a string containing a Python literal.

To simplify I’ll use a lambda expression.

import ast

min_max = lambda t: [min(t),max(t)]

try:
  t = ast.literal_eval(input("Digite sua lista: "))
except ValueError:
  t = [0];

print(min_max(t))

Examples:

Digite sua lista: 2,3,3,34
[2, 34]
Digite sua lista: [2,67,333, 0,-2324,8]
[-2324, 333]

Browser other questions tagged

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