2

I am trying to better understand recursion.

As an example, here are two definitions for calculating n! :

def factorial(num, p=1):
    if num == 0:
        return p
    else:
        p *= num
        return factorial(num-1,p)

and

def factorial(num):
   if num == 1:
       return num
   return num * factorial(num - 1)

Is one better than the other? I understand that the second one builds a call stack, while the first is calculating p at each step and just passing it to another iteration of the function. Are there separate names for these types of functions? Is the first one not recursion?

Just looking for some guidance on understanding the differences here. Thanks!

Community
  • 1
  • 1
David R.
  • 21
  • 2

1 Answers1

0

There is little difference between the two. I would say "simpler is better" and the 2nd one involves fewer variables so I would go for that one.

Or something even simpler:

  def factorial(N): return max(1,N) if N<3 else N*factorial(N-1)

In real life though, you shouldn't implement it recursively because iterative solutions will be faster.

Alain T.
  • 40,517
  • 4
  • 31
  • 51