Reputation: 1
I want to find the maximum and minimum in a user provided list of numbers.
value = input("Please enter an integer separated by commas. :")
i = value.split(',')
value1 = max(i)
value2 = min(i)
print("max =", value1)
print("min =", value2)
Executing the code and entering 1,2,4,36,5
results in
Please enter an integer separated by commas. :1,2,4,36,5
max = 5
min = 1
Why does the max()
function return 5
instead of 36
?
Upvotes: 0
Views: 483
Reputation: 4472
You should cast all the i
elements to int
value = input("Please enter an integer separated by commas. :") #input 1,2,4,36,5
i=[int(el) for el in value.split(',')]
value1 = max(i)
value2 = min(i)
print("max =", value1)
print("min =", value2)
OR
i = [int(el) for el in input("Please enter an integer separated by commas. :").split(',')] #input 1,2,4,36,5
value1 = max(i)
value2 = min(i)
print("max =", value1)
print("min =", value2)
Output
max = 36
min = 1
The original code made that elements in i
as strings ['1', '2', '4', '36', '5']
so they just need to be changed to ints and that made the min
and max
functions to work properly.
Upvotes: 1
Reputation: 1767
Convert it into integer to get proper results
value = input("Please enter an integer separated by commas. :")
i=value.split(',')
i = [int(x) for x in i]
value1 = max(i)
value2 = min(i)
print("max =", value1)
print("min =", value2)
OR
value = input("Please enter an integer separated by commas. :")
i=[int(x) for x in value.split(',')]
value1 = max(i)
value2 = min(i)
print("max =", value1)
print("min =", value2)
Upvotes: 1
Reputation: 13349
They are in string format that's why. Just map them to integer.
value = input("Please enter an integer separated by commas. :")
i=list(map(int, value.split(','))) #<---- Here
print(i)
value1 = max(i)
value2 = min(i)
print("max =", value1)
print("min =", value2)
Upvotes: 1