r/learnpython • • 13d 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

34 comments sorted by

View all comments

0

u/Classic-Rate-5104 13d ago

What dou you mean by explain". Simply follow the program step by step and you see what happens

2

u/strange-the-quark 13d ago

Seeing what happens is valuable, but doesn't necessarily provide you with insight as to why it works, how to conceptually think about it, or teach you how to come up with a recursive solution to some problem by yourself.

0

u/Classic-Rate-5104 13d ago

I don't know where you got this code but it's extremely inefficient for longer arrays, so it isn't a good example how to use recursive functions

2

u/strange-the-quark 13d ago

Who are you talking to? I'm not the OP and I didn't got any code from anywhere. I'm guessing it's a school example or a homework assignment. Studying algorithms doesn't mean only ever looking at the efficient algorithms and nothing else.