Finding the minimum value in a list recursively

I am trying to find the minimum value in a list recursively. Since I'm still new to adapting to a recursive method, I would like to get some help regarding my line of code:

listA = [9,-2,6,1,80,9,-2]

def findMinimum(l):
    if len(l) == 1:
       return l

    else:
       minNumber = findMinimum(l-1)
       min = listA[0]
       for i in listA:
           if listA[i]<listA[i+1]:
            min = listA[i]
            return min

findMinimum(listA)

I would be grateful if anyone could help me, as I am relatively new to recursion, and my understanding certainly matches the standard.

+4
source share
2 answers

The first part of your function is correct. But you have to change the second part as follows:

listA = [9,-2,6,1,80,9,-2]

def findMinimum(l):
    if len(l) == 1:
       return l[0]

    else:
       return min(l[0], findMinimum(l[1:]))

findMinimum(listA)

Remember that recursive functions simplify and simplify our codes.

+3
source

, . -, listA ; listA , l. ( len(l) == 1) l[0] ( - ). findMinimum ( , ); , , , l, , l[1:]. minNumber l; , l[0] l[1:]. , .

, , ; , !

, :

listA = [9,-2,6,1,80,9,-2]

def findMinimum(l):
    if len(l) == 0:
       raise ValueError('Cannot find the minimum of an empty list.')
    elif len(l) == 1:
       return l[0]
    else:
       minNumber = findMinimum(l[1:])
       min = l[0]
       if minNumber < min:
            min = minNumber
       return min

findMinimum(listA)
+2

Source: https://habr.com/ru/post/1679250/


All Articles