'How do i make a recursive function in python which does the following? magic list

I've got an assignment in which I need to code a recursive function (with no loops) in python that returns: [[]] if n is 1 [[],[[]]] if n is 2 [[],[[]],[[],[[]]]] if n is 3 a pseudo code or a hint would be really appreciated my current code which im working on:

def ezr(n,a,b):
    a.append(b)
    b= deepcopy(a)
    return ezr(n-1,a,b)

def magic_list(n):
    return ezr(n,[],[])

ive got stuck with first function



Solution 1:[1]

Generally recursion is the thing you should follow, but you have to work yourself on exit condition and how to receive data from recursion stack.

For now I see there are two problems, your recursion is infinite (wouldn't work for any call). Second is gathering data from your stack.

This should be enough to give you a lead to solve it on your own :)

from copy import deepcopy

def magic_list(n,a=[], b=[]):
    if n == 1:
        return []
    a = deepcopy(b)
    a.append(magic_list(n-1,a,b))
    return a

print(magic_list(1)) # []
print(magic_list(2)) # [[]]
print(magic_list(3)) # [[[]]]

If you strugle with visualization, use pythontutor.com

Visualization of execution step by step of code above: https://pythontutor.com/visualize.html#code=%0Afrom%20copy%20import%20deepcopy%0A%0Adef%20magic_list%28n,a%3D%5B%5D,%20b%3D%5B%5D%29%3A%0A%20%20%20%20if%20n%20%3D%3D%201%3A%0A%20%20%20%20%20%20%20%20return%20%5B%5D%0A%20%20%20%20a%20%3D%20deepcopy%28b%29%0A%20%20%20%20a.append%28magic_list%28n-1,a,b%29%29%0A%20%20%20%20return%20a%0A%0Aprint%28magic_list%281%29%29%20%23%20%5B%5D%0Aprint%28magic_list%282%29%29%20%23%20%5B%5B%5D%5D%0Aprint%28magic_list%283%29%29%20%23%20%5B%5B%5B%5D%5D%5D%0A&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false

Solution 2:[2]

def magic_list(n, a=[]):
    a.append(a.copy())

    if n - 1:
        return magic_list(n - 1, a)
    else:
        return a

for n = 3:

print(magic_list(3))

Output:

[[], [[]], [[], [[]]]]

for n = 2:

print(magic_list(2))

Output:

[[], [[]]]

for n = 1:

print(magic_list(1))

Output:

[[]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guaz
Solution 2