Python recursive function that returns the largest and smallest value within a list

Asked

Viewed 919 times

-1

Could someone help me with a light? I can do the recursive function to find the lowest value in a list, and the highest value separately. But a function returning the two together I cannot.

The exercise would be: Write a function, called minmax, that takes a list and returns a TUPLE containing the minimum element and the maximum element of the list. Its function must be recursive.

Do not use the Python "max" or "min" command over the list. EXAMPLES:

minmax([1,2,3]) = (1, 3)
minmax([49, 1, 6, 10]) = (1, 49)

My code:

def minmax(lista):

    if(len(lista) == 0):
        raise ValueError('Cannot find the maximum of an empty list.')

    if len(lista) == 1:
        return (lista[0], lista[0])
    else:
        maxValue = minmax(lista[1:])
  • Did you even try returning the two values? What was the result obtained?

  • he returns Valueerror('Cannot find the Maximum of an Empty list.')

  • So put the code to the question and we’ll see what we can do.

  • All right, I got it!

  • 1

    could do the Sort first and then take the first and last value

1 answer

1


You got too close to the solution. You only missed returning when the number in the list is greater than 1. You calculate the minimum and maximum of the rest of the list, but do nothing with the result. The idea here is to compare the minimum and the maximum that you got from the rest of the list with the first number of the list, because this may be less than the minimum or greater than the maximum, so it would be:

def minmax(lista):

    if(len(lista) == 0):
        raise ValueError('Cannot find the maximum of an empty list.')

    if len(lista) == 1:
        return (lista[0], lista[0])

    _min, _max = minmax(lista[1:])

    if lista[0] < _min:
        _min = lista[0]

    if lista[0] > _max:
        _max = lista[0]

    return (_min, _max)

This way you will be calculating recursively and get the right results.

  • Wow, thank you so much! Now I managed to understand, missed the comparison ne?! thank you!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.