Return the largest number in Python with recursion

2

My teacher started talking about recursion, and spent some exercises, only that I caught on one.

As I said in the statement below, I should create a function that returns the largest value contained in a list.

My problem is: I can not do this using recursion. My idea was to type a bubble sort and then only display the last element, however, the following error is occurring:

  

RecursionError: maximum recursion depth exceeded in comparison

I can not think of another way to do it.

Recursively implement a Max function that returns the highest value stored in a V vector, containing n integers

global c
global c2
global temp

x = [5, 2, 8, 4, 6, 9, 0, 1]

c = 0
c2 = 1
temp = max(x)

def Max(x):
    global c
    global c2
    if x[c] > x[c2]:
        x[c], x[c2] = x[c2], x[c]
        c += 1
        c2 += 1
    if x[len(x)-1] != temp:
        Max(x)
    return x

print(Max(x))
    
asked by anonymous 19.06.2018 / 19:58

1 answer

1

You must have realized that it is not the idea of this site that people solve the problem for you - but you can give them tips.

In the case of recursive function, the idea is always: the function checks to see if it has a trivial answer - in this case it would just receive an empty list and another parameter that would be "candidate for maximum value". Since the list has no more elements, the maximum candidate is the maximum itself - it has no other competitors - and the value is returned.

If the list is not empty, it will have a list with some elements and a candidate at its maximum - it can extract the last element from the list (the .pop() method does this), check if this element is larger that the current candidate - if so, replaces the candidate. At that point, you have a shorter list and an up-to-date candidate, and you need to decide what to return to who called the original function (and make use of recursion). I will not finish describing everything - the exercise continues with some challenge.

Another tip: Global variables are not required in this problem. Its recursive function will need two parameters - the list and a "candidate for maximum".

I hope these tips help you

    
19.06.2018 / 20:12