【发布时间】:2020-11-16 02:51:54
【问题描述】:
我有这个程序,其中函数有一个 for 循环,如下所示,我在其中递归调用相同的函数。
class soln(object):
def test(self, start, end):
for i in range (start, end):
print ("here1 i %d" % i)
if (i==2):
return 6
i = self.test(i+1, end)
print(i)
my = soln()
my.test(0,4)
output is
here1 i 0
here1 i 1
here1 i 2
6
here1 i 2
I expected to see i to be 6 not 2
即使我在从递归调用返回后更改了迭代器的值,迭代器仍会返回到它的旧值。堆栈将返回到迭代器 i 应该具有新值的前一个堆栈。也许我有点愚蠢地理解这一点并欣赏一些信息以及如何将 i 更改为递归调用的返回值?
【问题讨论】:
-
在 for 循环中更改循环值不是一个好习惯 - 正如您所注意到的,很难预测它会得到哪个值
-
@stefan 我们可以有逻辑(假设没有递归但有一些其他逻辑),并且取决于我可以改变我不是吗?例如:
after the return call instead of recursion, I can do i += 4。那我换不行吗?