Click here to Skip to main content
14,767,355 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.

Example:
high_and_low("1 2 3 4 5") # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"

What I have tried:

def high_and_low(numbers):
    li = numbers.split()
    mx = max(li)
    mn = min(li)
    return str(mx)+" "+str(mn)
print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))


I am getting 6 -214
Posted
Updated 12-Aug-19 17:43pm

Quote:
I am getting 6 -214

Just a guess: you forgot to convert each element of li to numbers.
numbers is a string, after split, you get a list of strings. Since you want to compare integer values of strings, you need to covert the list of strings to a list of integers.
Quote:
Why in string "6" is greater than others? How max function works on string. In my opinion it uses the number of charaters in the string but this does seem to be the case here.

Sorted strings are in same order as words in a dictionary.
-24 < -52 < 1 < 11 < 15 < 2 < 25< 2614 < 3 < 33 < 4
   
v2
Comments
Member 14517556 13-Aug-19 1:48am
   
Why in string "6" is greater than others? How max function works on string. In my opinion it uses the number of charaters in the string but this does seem to be the case here.
Richard MacCutchan 13-Aug-19 4:28am
   
'6' is considered highest because it is the highest when the characters are sorted in alphabetical order.
def high_and_low(numbers):
    li =[int(x) for x in list1.split(' ')]
    mx = max(li)
    mn = min(li)
    return str(mx)+" "+str(mn)
print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900