I'm trying to write a function that returns the highest and lowest number in a list.
def high_and_low(numbers):
return max(numbers), min(numbers)
print(high_and_low("1 2 8 4 5"))
But I have this result:
('8', ' ')
Why do I have ' '
as a lowest number?
You are passing string to a function. In order to achieve the desired result, you need to split the string and then type-cast each element to int
. Then only your min
and max
function will work expectedly. For example:
def high_and_low(numbers):
# split numbers based on space v
numbers = [int(x) for x in numbers.split()]
# ^ type-cast each element to `int`
return max(numbers), min(numbers)
Sample Run:
>>> high_and_low("1 2 8 4 5")
(8, 1)
Currently your code is finding the minimum and maximum value based on lexicographical order of the characters.
In order to achieve your desired result you can call split()
on the string you are passing in. This essentially creates a list()
of your input string—which you can call the min()
and max()
functions on.
def high_and_low(numbers: str):
"""
Given a string of characters, ignore and split on
the space ' ' character and return the min(), max()
:param numbers: input str of characters
:return: the minimum and maximum *character* values as a tuple
"""
return max(numbers.split(' ')), min(numbers.split(' '))
As others have pointed out you can also pass in a list of values you'd like to compare and can call the min and max functions on that directly.
def high_and_low_of_list(numbers: list):
"""
Given a list of values, return the max() and
min()
:param numbers: a list of values to be compared
:return: the min() and max() *integer* values within the list as a tuple
"""
return min(numbers), max(numbers)
Your original functions does technically work, however, it is comparing numerical values for each character and not just the integer values.
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