2

Given some number n, I want to produce a list of size n where the following example shows how the n'th element in the list should be:

  • For n=0: return []
  • For n=1: return [[]]
  • For n=2: return [[],[[]]]
  • For n=3: return [[], [[]], [[], [[]]]

Basically it takes the precedent lists and append them into a new list.

I've tried the following:

def magic_list_helper(n, lst):
    if n == 0:
        return lst
    if n == 1:
        lst.append([])
        return magic_list_helper(n-1,lst)
    if n > 1:
        magic_list_helper(n-1, lst)
        new_list = []
        new_list.append(lst[n - 2])
        lst.append(new_list)
        return lst

but for n=3 I get [[], [[]], [[[]]]].

4

1 Answer 1

1

There are a few things to notice. First, how will you set your recursion up in a way that produces said output. Well, your output is of the form [f(0), f(1), f(2) ... f(n)] for recursive function f. The following does exactly that:

def magic_list_helper(n):
    return [] if n == 0 else [magic_list_helper(n-i) for i in range(1,n)]

If n=0, it returns an empty list, else, it is going to return [f(0), f(1), f(2) ... f(n)], and this, will then return [f(0), f(1), f(2) ... f(n-1)] and so on.

Sign up to request clarification or add additional context in comments.

2 Comments

Im sorry I forgot to add that I cant use for loops
Any for loop can be refactored to recursion or a while loop (not that it's a good idea in general, just to fulfill arbitrary requirements).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.