简体   繁体   English

为什么python中递归function会出现Memory错误?

[英]Why is there Memory Error in recursion function in python?

I wrote a code to get all subsequences of a string using recursion in python.我编写了一个代码来使用 python 中的递归来获取字符串的所有子序列。 Below is the code.下面是代码。

def solve(s):

    if (len(s)==0):
        return [""]
    curr = s[0]
    res = s[1:]
    ans = solve(res)
    for i in ans:
        ans.append(curr+i)
    return ans
if __name__=="__main__":
    s=str(input())
    print(solve(s))

For input = "ab", the above code is throwing Memory Error对于 input = "ab",上面的代码抛出Memory 错误

I am not sure why is it happening.我不确定为什么会这样。

On changing the code to following one, it works.在将代码更改为以下代码时,它可以工作。

def solve(s):

    if (len(s)==0):
        return [""]
    curr = s[0]
    res = s[1:]
    ans = solve(res)
    new = []
    for i in ans:
        new.append(i)
        new.append(curr+i)

    return new

if __name__=="__main__":
    s=str(input())
    print(solve(s))

Can someone please explain what is the reason behind Memory Error in first code?有人可以解释第一个代码中Memory 错误背后的原因是什么吗? Thanks in advance.提前致谢。

This:这个:

for i in ans:
    ans.append(curr+i)

You are iterating through ans and adding stuff onto the end of ans at the same time.您正在遍历ans并同时将内容添加到ans的末尾。 It is an infinite loop: you'll never get to the end of ans because you keep making it longer (until you run out of memory).这是一个无限循环:你永远不会到达ans的尽头,因为你不断地让它变长(直到你的内存用完)。

If you want to add new elements to ans which are each of the existing elements preceded by curr , you can do that with a list comprehension:如果您想向ans添加新元素,这些新元素是curr前面的每个现有元素,您可以使用列表推导来做到这一点:

ans += [curr + i for i in ans]

This way computes all the new elements, and then adds them all onto ans , instead of extending ans as it goes.这种方式计算所有新元素,然后将它们全部添加到ans中,而不是扩展ans

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM