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

Time:05-15

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

CodePudding user response:

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= 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)) # [[[]]] &cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=[]&textReferences=false

CodePudding user response:

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:

[[]]
  • Related