Unexpected maximum number, but correct minimum number

What I want: Printout ('542', '-214')

What's currently going on: Prints out ('6', '-214')

I'm not sure why the minimum number is correct, but 6 is used as the maximum.

My Python code:

def high_and_low(numbers):

    numbers = numbers.split(" ")
    maxNumbers = max(numbers)
    minNumbers = min(numbers)

    numbers = maxNumbers, minNumbers

    return numbers

print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))  

      

I tried to change this to:

maxNumbers = int(max(numbers))
minNumbers = int(min(numbers))

      

But 6 is still coming back.

+3


source to share


3 answers


This works for me:

def high_and_low(numbers):

    numbers = [int(n) for n in numbers.split(" ")]
    maxNumbers = max(numbers)
    minNumbers = min(numbers)

    numbers = maxNumbers, minNumbers

    return numbers

print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))  

      

Result:



(542, -214)

      

When you tried casting max()

and min()

how int

, you are late, as the values ​​have already been evaluated based on the rank of various strings in your list. Passing in values int

before evaluating their rank is the correct way to get the result you are looking for.

+3


source


Well, you are sorting strings, not ints. What you were trying to do with `int (max (numbers)) only changes the" max string "to int.

You need to change the values ​​to int before checking for the maximum and minimum value. This will work:



def high_and_low(numbers):

    numbers = [int(x) for x in numbers.split(" ")]
    maxNumbers = max(numbers)
    minNumbers = min(numbers)

    numbers = maxNumbers, minNumbers

    return numbers

print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))

      

+1


source


mobile recording, sorry if formatting sucks. you need to inject string values ​​into numeric (integer, float) types.

def high_and_low(numbers):
    a =[int(i) for i in numbers.split(" ")]
    return max(a), min(a)

      

0


source







All Articles