【问题标题】:variables modified in a recursive function python 3在递归函数python 3中修改的变量
【发布时间】:2017-05-16 01:10:06
【问题描述】:
 def foo():
     l = [0, 0, 0]
     for i in range(3):
         l[i] = random.random()
         for j in l:
            if j > 0.5:
                for i in range(3):
                    l[i] = random.random()
                foo()
            else:
               print("Returning...")
               return None
      return None

我的递归函数修改了一个列表l。在迭代l 时,递归调用是嵌套的。问题是当从嵌套调用返回时,for 循环正在迭代的列表将是不同的列表(因为在嵌套调用期间l 被覆盖)。

示例:l = [0.7, 0.5, ...] 第一次执行foo(),然后是j = 0.7;让我们假设l 变为 l = [0.3, 0.86, ...]foo() 的第一个嵌套调用中;当foo() 返回时,我需要j 取值0.5,但这不会发生,因为在此期间l 已被覆盖。

那么,我如何在递归函数中使用(修改)列表l,同时确保在l 开始迭代后,它会在同一个列表上完成,直到结束?

【问题讨论】:

  • sorry....在for循环中,调用的是foo(),而不是foo(count)
  • 您可以编辑您的帖子并删除count 编辑链接就在帖子文本下方。
  • 你没有在递归中修改列表。
  • 当我们不知道这个函数应该做什么时,很难纠正你的逻辑。
  • 我们需要一个规范的“为什么我的递归函数不起作用?” – 我看到人们几乎每天都在编写没有return 的递归调用

标签: python python-3.x recursion


【解决方案1】:

正如其他评论员所指出的,如果没有更多信息,很难给出具体建议。但是,传递了您问题的关键点,我想说您需要考虑将列表 l 作为参数传递给每个递归调用,然后将每个修改作为 foo 的结果返回。也就是说,每个递归调用都可以在整个计算过程中处理“相同”列表,并最终在顶层返回答案。

【讨论】:

    【解决方案2】:

    当我们不知道这个函数应该做什么时,很难纠正你的逻辑。让我们注释一下该函数的作用,并希望您能看到您的逻辑错误:

    def foo():
         # Create a local list l
         l = [0, 0, 0]
    
         # Ignore those initial zeroes;
         #   replace each in turn with a random number
         for i in range(3):
             l[i] = random.random()
    
             # Grab the next number in the list;
             #   this is the one we just generated.
             for j in l:
                # If that number is greater than 1/2,
                #   rewrite the entire local list.
                # Then recur on foo.
                if j > 0.5:
                    for i in range(3):
                        l[i] = random.random()
                    foo()
                # If any element of the rewritten list is less than 1/2,
                #   return now.
                else:
                   print("Returning...")
                   return None
          return None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 2019-05-28
      相关资源
      最近更新 更多