Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find highest and lowest number from the string of numbers

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?

like image 386
ladybug Avatar asked Dec 23 '22 11:12

ladybug


2 Answers

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.

like image 195
Moinuddin Quadri Avatar answered Dec 28 '22 05:12

Moinuddin Quadri


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.

like image 37
eric Avatar answered Dec 28 '22 06:12

eric