Problem statement - Take 3 numbers as input array (without using map function) and print the min and max values in the array
My solution-
arr = input("Enter numbers ") #1 2 3
print(min(arr)) #returns empty
print(max(arr)) #returns 3
Question- Why does max(arr) return the correct output and min(Arr) return an empty string?
CodePudding user response:
The issue is that input returns a string and not an array of numbers. You'd have to split the numbers into a list and convert them to integers before you can calculate which is the minimum and which is the maximum:
arr = list(map(int, input("Enter numbers ").split(" ")))
print(min(arr))
print(max(arr))
Or if you'd like to avoid the map function, you can do it like this:
arr = []
for num_str in input("Enter numbers ").split(" "):
arr.append(int(num_str))
print(min(arr))
print(max(arr))
min and max receive a list of objects as input and return the lowest/highest object in the list, respectively.
When you pass the string "1 2 3" to the min function the min function treats that string as a list of characters: ['1', ' ', '2', ' ', '3']. The character " " is considered lower than "1" "2" and "3" so it's returned by min.
When you pass the string "1 2 3" to the max function the max function treats that string as a list of characters: ['1', ' ', '2', ' ', '3']. The character "3" is considered higher than "1" "2" and " " so it was returned by max.
