返回如何参考以下代码在递归中工作 [英] how the return is working in recursion with reference to the following code

查看:47
本文介绍了返回如何参考以下代码在递归中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def subs(l):
    if l == []:
        return [[]]

    x = subs(l[1:])

    return x + [[l[0]] + y for y in x]

1) 我试图理解上述代码的工作

1) I am trying to understand working of the above code

2) 如果 l = [1,2,3] 在递归结束时我们将得到一个空的 list 列表

2) If l = [1,2,3] at the end of the recursion we will get an empty list of list

3) 在下一次迭代中,我们将得到 x 的结果为 3(我想它会进入下一步,即return)

3) In last next iteration we will be given the result to the x will be 3 (I am thinking it will go to the next step which is return)

4) 在这些 returns 我想它会添加 return x + [[l[0]] + y for y in x] 应该返回 (3,3).

4) In these returns I am thinking it will add return x + [[l[0]] + y for y in x] should return (3,3).

5) 结束这些步骤后,答案应该是 (3,3).

5) By ending of these step the answer should be (3,3).

根据第二步的最终答案必须是[[],[3,3]].

The final answer according to be at the second step must be [[],[3,3]].

但代码打印出不同的答案.

But the code is printing a different answer.

o/p 

[], [3]]

谁能解释我的假设哪里出错了,以及这些步骤如何return x + [[l[0]] + y for y in x]?

Can any one explain where my assumption went wrong and how return x + [[l[0]] + y for y in x] these steps are working?

推荐答案

我对代码进行了一些修改以使其打印中间结果:

I made some modifications to the code to make it print intermediate results:

def subs(l, num=0):

    print(' ' * num, 'current l is:', l)
    print()

    if l == []:
        return [[]]

    x = subs(l[1:], num + 4)
    print(' ' * num, 'current x is:', x)

    answer = x + [[l[0]] + y for y in x]
    print(' ' * num, 'current answer is:', answer)

    print()

    return answer

subs([1, 2, 3])

让我们看看输出(这是一个图像):

缩进描述了复活深度.黑色箭头表示计算流程.红色箭头表示哪些 lx 相互对应(属于同一命名空间).从图中可以看出递归与循环有何不同.递归一直下降到微不足道的情况,然后上升.注意红色箭头.

Indentation depictures resursion depth. Black arrows show calculation flow. Red arrows show which l and x correspond to each other (belong to the same namespace). From the image one can see how recursion differs from loops. Recursion goes all the way down to the trivial case and then goes up. Pay attention to the red arrows.

所以,首先,x 永远不会是 3.简直不可能是真的.其次,l 可以是 [3].对应的x是最后递归步骤返回的[[]](平凡情况).这些值给你答案 [[], [3]].这是前面 l = [2, 3]x.

So, first, x is never 3. It just can't be actually. Second, l can be [3]. Corresponding x is [[]] returned by the final recursion step (trivial case). These values give you answer [[], [3]]. And this is x for the previous l = [2, 3].

这篇关于返回如何参考以下代码在递归中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆