Reputation: 13
I am trying to create a function which finds the max number in a list (without using the max() command)
however my function doesn't work for negative numbers I don't think? how do I fix this? thanks! for example in my second print test it prints 0 instead of -3.
def my_max(data):
"""finds max number in list"""
maximum = 0
for num in data:
if num > maximum:
maximum = num
return maximum
print(my_max([11, 99, 3, -6]))
print(my_max([-3, -5, -9, -10]))
Upvotes: 1
Views: 2842
Reputation: 528
You have 2 solutions to that:
-10000000
(won't work in any case and is ugly) or -math.inf
(will work in any case but is still ugly)Putting the first item of your list as initial maximum (data[0]
) (will work in any case).
Explanation for this 2nd solution : If the first item of your list is the biggest one, the condition will always resolve to False
and this inital maximum will be returned, or, it'll replace it by an other bigger item in the list and finally return the biggest.
Upvotes: 1
Reputation: 1611
One of the more obscure number types in Python is math.inf
-- infinity. This can be produced by:
from math import inf
, and then using inf
or -inf
(negative infinity),
or
float("inf")
for positive infinity, and float ("-inf")
for negative infinity
Upvotes: 0
Reputation: 42129
This is because you are initializing you maximum variable with an arbitrary value (zero) that is already larger than -3. Try initializing it with the first element in the list maximum = data[0]
Upvotes: 2