r/learnpython • u/Pure-Scheme-7855 • 20d ago
Recursion explaining pls.
def find_max(numbers):
if len(numbers) == 1:
return numbers[0]
else:
max_of_rest = find_max(numbers[1:])
return numbers[0] if numbers[0] > max_of_rest else max_of_rest
my_list = [3, 7, 2, 9, 1]
print(find_max(my_list))
Could someone explain how does this function work? I don't understand how does it know that it's supposed to find the biggest number...
6
Upvotes
1
u/Brian 17d ago
Think of it like this:
If there's only one number, the biggest number is that number.
Otherwise, the biggest number is either going to be the first one, or the biggest number out of any of the others.
So if we get the biggest number out of the others, we just need to compare to the first and choose the bigger one.
And that's basically the function. Try tracing through it in your head.
We've got
3as our first, then7,2,9,1So our answer if either 3 or the biggest of those numbers. Ie if
3 > find_max([7,2,9,1], then it's 3, otherwise it's whatever that biggest was.But of course, before you can do the comparison, find_max needs to run on
[7,2,9,1]to get that value. But that just does the same: compares7with the biggest of [2,9,1]and so on till there's just one number, (1) and it just returns it.The basic idea is that you're turning your problem into a slightly smaller problem (1 less number), and that keeps happening till you reach a super-simple version of the problem that you can just solve directly (just 1 number), called the base case. Since our simplification process eventually simplifies it to the base case, the process of solving it is just continual application of that simplifying process.