Why is a factorial recursive function iterating from lowest to highest number and not from highest to lowest number?

Question:

I have this simple recursive function, which is calculating the factorial of a number. The result is good and it works like a charm.

def factorial(y):
  if y == 0:
    return 1

  elif y == 1:
    return 1

  else:
    result = y * factorial(y - 1)
    print(result)

return result

To understand the process I’ve added the print(result) function to see the value of the result variable at each iteration of the recursive function.

The output is:
2
6
24
120

I was expecting this output instead :
120
24
6
2

So, why is my recursive function iterating from the lowest number to the highest and not from the highest to the lowest number ?

Asked By: PhpDoe

||

Answers:

When result = y * factorial(y - 1) is evaluated, the multiplication can only take place when both operands are evaluated first. So first the recursive call has to be made. This means that no multiplication will take place before all recursive calls have been initiated. Only when the recursion "unwinds" and the callers get their needed operand value for it, will the multiplications be evaluated.

In other words, it is "on the way back", out of recursion that the multiplication operator is accumulating the factors (left-side operands) with the previous product (right-side operand) into a new product.

Answered By: trincot

The inner-most call finishes first, so that one prints first.

The outer-most call is only ready once all the inner calls finish, so it necessarily has to be printed only after the inner calls finish.

Try this for funsies:

def factorial(y, level=0):
  if y == 0:
    return 1

  elif y == 1:
    return 1

  else:
    print(level*" ", "pre-call, y=", y)
    result = y * factorial(y - 1, level=level+2)
    print(level*" ", "post-call, result=", result)

  return result


factorial(5)

Output is:

 pre-call, y= 5
   pre-call, y= 4
     pre-call, y= 3
       pre-call, y= 2
       post-call, result= 2
     post-call, result= 6
   post-call, result= 24
 post-call, result= 120

The nesting helps show the recursion level.

Answered By: Claudiu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.