I am trying to return the min and max of a string of numbers, ie. ("1 2 3 4 5 6")
The code that I came up with is as follows
def high_and_low(numbers):
numbers = numbers.split(' ')
map(int, numbers)
return str(max(numbers)) + ' ' + str(min(numbers))
This code does not work for the following example:
print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
6 -214
However, a similar function crafted as:
def min_and_max(numbers):
nn = [int(s) for s in numbers.split(' ')]
return "%i %i" % (max(nn),min(nn))
Returns the correct answer
print(min_and_max("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
542 -214
Shouldn't
map(int, numbers)
be the same as
[int(number) for number in numbers]
Why do the two functions not return the same values?
In your high_and_low method, map(int, numbers) is not being assigned to a value.
def high_and_low(numbers):
numbers = numbers.split(' ')
numbers = map(int, numbers)
return str(max(numbers)) + ' ' + str(min(numbers))
Also, map returns an iterator in Python 3.x. Your min(numbers) will error because max will exhaust the iterator and throw a ValueError due to an empty sequence. So you need to convert it to a list
def high_and_low(numbers):
numbers = numbers.split(' ')
numbers = list(map(int, numbers))
return str(max(numbers)) + ' ' + str(min(numbers))
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