有人可以解释这种递归是如何工作的吗?

时间:2015-05-20 12:27:32

标签: python recursion

我无法弄清楚它是如何工作的。

def exp(x,n): 
   if n == 0:
      return 1
   else:
      return x * exp(x, n-1)

print(exp(2, 4))

答案是16。

2 个答案:

答案 0 :(得分:1)

exp(2, 4) = 2 * exp(2, 3) 
          = 2 * ( 2 * exp(2, 2) )
          = 2 * ( 2 * ( 2 * exp(2, 1) ) )
          = 2 * ( 2 * ( 2 * ( 2 * exp(2, 0) ) ) )
          = 2 * ( 2 * ( 2 * ( 2 * 1 ) ) )

答案 1 :(得分:0)

手工减少:

? print(exp(2, 4))
! calculate( exp(2,4) ) and print the result
? exp(2,4)   matches the definition:
  exp(x,n)   with x=2, n=4
! substitute the variables in the function's body:
  if 4==0: return 1
  else: return 2 * exp(2, 4-1)
! 4==0 is false
? 2 * exp(2, 3)
.........
  2 * ( 2 * exp(2, 2) )
.........
  2 * ( 2 * ( 2 * exp(2, 1) ) )

你能完成序列吗?

相关问题