简体   繁体   中英

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

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM