This is my current program. It's outputting the incorrect max and min. What is missing from my if statement?
def palin():
max = 0
min = 50
numbers = "23","3","4","6","10"
for x in numbers:
if x>max:
max=x
if x<min:
min=x
print max
print min
When you do string comparisons or try to use min()
, max()
with strings, you are actually maintaining alphabetical ordering:
>>> sorted(numbers)
['10', '23', '3', '4', '6']
This is why a lot of the built-in Python functions that rely on positional comparison support the key
argument:
>>> numbers
('23', '3', '4', '6', '10')
>>> sorted(numbers, key=int)
['3', '4', '6', '10', '23']
>>> min(numbers, key=int)
'3'
>>> max(numbers, key=int)
'23'
Your numbers are strings. First convert them to integers:
numbers = [int(num) for num in numbers]
def palin():
max = 0
min = 50
numbers = "23","3","4","6","10"
numbers = [int(num) for num in numbers]
for x in numbers:
if x>max:
max=x
if x<min:
min=x
print max
print min
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With