简体   繁体   中英

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

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? 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. 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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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