how the return is working in recursion with reference to the following code

六月ゝ 毕业季﹏ 提交于 2020-01-24 00:21:25

问题


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

    x = subs(l[1:])

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

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

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

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) In these returns I am thinking it will add return x + [[l[0]] + y for y in x] should return (3,3).

5) By ending of these step the answer should be (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]]

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


回答1:


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])

Let's have a look at the output (it's an image):

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.

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].



来源:https://stackoverflow.com/questions/55113683/how-the-return-is-working-in-recursion-with-reference-to-the-following-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!