Return the largest number in Python with recursion

Asked

Viewed 642 times

2

My teacher started talking about recursion, and passed a few exercises, only I stalled on a.

As stated in the following statement, I must create a function that returns the highest value contained in a list.

My difficulty is: I’m not able to do this using recursiveness. My idea was to make like one Bubble Sort and then only display the last element, however, the following error is occurring:

Recursionerror: Maximum recursion Depth exceeded in comparison

I can’t think of any other way.

Recursively implement a function Max returns the largest value stored in a vector V, containing n integer

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))
  • Your identation is not correct. This in Python is a syntax error, and makes it very difficult to track your ideas. I think you should have ided Scroll the line with the space bar to format the question - this is not necessary. Edit the question, paste the cmo code is in your editor, select the code snippet and press the button {} to format the code here, please.

  • I didn’t know that. Thank you :)

1 answer

1


You may have noticed that it is not the idea of this site that people solve the problem for you - but tips can be given.

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

If the list is not empty, it will have in hand a list with some elements and a candidate at most - it can extract the last element from the list (the method .pop() does this), check whether this element is greater than the current candidate - if yes, it replaces the candidate. At this point, you have at hand a shorter list and an updated candidate - and you need to decide what to return to who called the original function (and make use of the recursion). I will not finish describing everything - then the exercise continues with some challenge.

Another tip: global variables are not needed in this problem. Your recursive function will need two parameters - the list and a "maximum candidate".

I hope these tips help you

  • Thank you so much for the tips. With them I managed to make the code

Browser other questions tagged

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