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 [[], [[]], [[[]]]].

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Le S
  • 41
  • 4
  • 1
    https://stackoverflow.com/questions/74752498/recursive-function-to-nested-lists/74757778#74757778 – Timmy Diehl Dec 12 '22 at 21:17
  • Does this answer your question? [Recursive function to nested lists](https://stackoverflow.com/questions/74752498/recursive-function-to-nested-lists) – Timmy Diehl Dec 12 '22 at 21:19
  • I forgot to add that I cant use for loops – Le S Dec 12 '22 at 21:37
  • See also [Generate increasing nested empty list structure with recursion](https://stackoverflow.com/questions/72186151/generate-increasing-nested-empty-list-structure-with-recursion/74756717#74756717) which is a closer spec match than [Recursive function to nested lists](https://stackoverflow.com/questions/74752498/recursive-function-to-nested-lists) but doesn't have an upvoted answer yet. – ggorlen Dec 12 '22 at 22:12

1 Answers1

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.

Lexpj
  • 921
  • 2
  • 6
  • 15
  • Im sorry I forgot to add that I cant use for loops – Le S Dec 12 '22 at 21:36
  • 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). – ggorlen Dec 12 '22 at 22:12