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