我在递归中使计数器工作时遇到问题,它不是打印 11,而是打印 11,1s。我哪里出错了?
def power(x, n):
global countcalls # note countcalls variable is in my global and it is equal to 0
countcalls = +1
print(countcalls)
if n <= 0:
return 1
else:
return x * power(x, n-1)
Run Code Online (Sandbox Code Playgroud)
我的输出:
1
1
1
1
1
1
1
1
1
1
1
1024
Run Code Online (Sandbox Code Playgroud)
想要的输出:
11
1024
Run Code Online (Sandbox Code Playgroud)
首先,countcalls = +1不增加变量,只是将其设置为1。要递增,请使用+= 1,而不是= +1。
其次,如果您只想在最后打印,请将print()调用放在基本情况中。
不要使用全局变量,而是使用另一个默认为 的参数0。
def power(x, n, countcalls = 0):
countcalls += 1
if n <= 0:
print(countcalls)
return 1
else:
return x * power(x, n-1, countcalls)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
195 次 |
| 最近记录: |