0

Grokking some algorithms via recursion and got a question

My task is to define a function, that will find maximum in the list via recursion. Can't made it by myself, looked in the "Answer" chapter, rewrite it and still can't understand def max(list): if len(list) == 2: #basic case, if list consists of 2 elements return list[0] if list[0] > list[1] else list[1] print (list[0], list [1], list[2]) #print to see what elements are selected sub_max = max(list[1:]) print (sub_max) #print to see what's in there at the moment return list[0] if list[0] > sub_max else sub_max print(max([1, 3, 17, 6, 23, 45, 2, 7, 11, 8, 29, 15, 20])) When I ran the code, the first thing shown is lists of three elements (i.e. 1, 3, 17; 3, 17, 6; till the last 29, 15,20). And then list of sub_maxs, as if the code runs from the end. Why does it happens so? I can't see it in the code (for now)

2nd Feb 2022, 7:33 PM
Egor Markov
Egor Markov - avatar
3 Antworten
0
I think sub_max = max(list[1:]) is minimizing list till the last 2 elements, and then returning back through 'call stack'. Am I right? Or I still don't get it?
2nd Feb 2022, 7:41 PM
Egor Markov
Egor Markov - avatar
0
def max(val,lst): if(len(lst)==1): if(val>lst[0]): return val else: return lst[0] if(val<lst[0]): val=lst[0] return(max(val,lst[1:])) lst=[1, 3, 17, 6, 23, 45, 2, 7, 11, 8, 29, 15, 20] print(max(lst[0],lst[1:]))
3rd Feb 2022, 7:24 AM
Adi Nath Bhawani
Adi Nath Bhawani - avatar
0
Check this one
3rd Feb 2022, 7:25 AM
Adi Nath Bhawani
Adi Nath Bhawani - avatar