-1
我无法弄清楚它是如何工作的。有人可以解释这种递归的工作原理吗?
def exp(x,n):
if n == 0:
return 1
else:
return x * exp(x, n-1)
print(exp(2, 4))
答案是16
我无法弄清楚它是如何工作的。有人可以解释这种递归的工作原理吗?
def exp(x,n):
if n == 0:
return 1
else:
return x * exp(x, n-1)
print(exp(2, 4))
答案是16
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)))
还原手:
? 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)))
就可以完成的顺序?
我投票结束这个问题作为题外话,因为它是简单的数学问题。 –
两条评论:1.您是否试图在纸上写* *执行?并不难。 2.如果'n'为负值会发生什么? – Barranka