Reputation: 23
def my_max():
#using input to collect number to list
list_a = input("print your list with numbers: ").split(",")
# Searching for the highest number
max = 0
for i in list_a:
if i > str(max):
max = i
print(max)
my_max()
When i write numbers to input, sometimes the highest number is being printed, but not always.
For an example, if i write :"54,64,446 " the number "64 is being printed. Do anybody knows why?
Upvotes: 2
Views: 200
Reputation: 26039
You need to map it into list of int
s before you do the logic:
def my_max():
# using input to collect number to list
list_a = input("print your list with numbers: ").split(",")
# Searching for the highest number
return max(map(int, list_a))
print(my_max())
Sample run:
print your list with numbers: 54,64,446
446
Splitting on ','
gives you a list of strings. What you observed is an expected behaviour because you find max of a list of strings in contrast to list of integers.
Without using a max()
, I would go something like this:
def my_max():
# using input to collect number to list
list_a = list(map(int, input("print your list with numbers: ").split(",")))
# Searching for the highest number
max = list_a[0]
for x in list_a[1:]:
if x > max:
max = x
return max
print(my_max())
Upvotes: 2
Reputation: 2441
Your list_a
contains strings, not numbers. When you do your comparison, you are comparing the values of these strings. The result of this is the highest value alphabetically, rather than numerically.
Taken as strings rather than numbers, 64 > 54 > 446
Upvotes: 0