def nest(x, n):
a = []
for i in range(n):
a.append([x])
return a
print nest("hello", 5)
This gives an output
[['hello'], ['hello'], ['hello'], ['hello'], ['hello']]
The desired output is
[[[[["hello"]]]]]
Every turn through the loop you are adding to the list. You want to be further nesting the list, not adding more stuff onto it. You could do it something like this:
def nest(x, n):
for _ in range(n):
x = [x]
return x
Each turn through the loop, x
has another list wrapped around it.
instead of appending you sould wrap x
and call recursively the method till call number is lesser than n
def nest(x, n):
if n <= 0:
return x
else:
return [nest(x, n-1)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With