【问题标题】:is stack doing something funny in my python program堆栈是否在我的 python 程序中做一些有趣的事情
【发布时间】: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 。那我换不行吗?

标签: python recursion stack


【解决方案1】:

我把for循环改成了这个

while (start < end):
...
start +=1

似乎适用于少数测试用例。但会检查更多测试。

【讨论】:

    【解决方案2】:

    您在返回之前正在打印。试试这个:

    class soln(object):
        def test(self, start, end):
            for i in range(start, end):
                if i == 2:
                    return 6
                print("here i %d" % i)
                i = self.test(i + 1, end)
                print("here i is", i)
    
    
    my = soln()
    my.test(0, 4)
    

    【讨论】:

    • 这不起作用,因为迭代器 i 在我们点击 for 循环(从前一个递归返回后)并将其值更改回较早的值并移动到 if 条件时
    猜你喜欢
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多