Home > Software design >  Recursive function to nested lists
Recursive function to nested lists

Time:12-11

I have tried to crate a recursive function that gets a number and returns a list of nested list according to the index. For example, for 0, the function returns an empty list []. for 1, the function returns [[], [[]]]. for 3 the function returns [ [] , [ [] ] , [ [] , [ [] ] ]], and so on.

def func(n):
    if n == 0:
        return []
    return [func(n-1)]

i have tried many different approaches for this problem. I cant figure out how to extend my output to nested list according to the task.

CodePudding user response:

What I think you're looking for is something like this:

def f(n):
    L = []
    for i in range(n):
        L.append(f(i))
    return L

My confusion stems from your examples. For n=0, there are 0 elements and for n=3 there are 3 elements, but there are 2 elements for n=1. This should work where n is the number of elements in the final list

CodePudding user response:

Each list actually contains all the preceding lists, not just the immediately preceding list. (Based on your example for func(3), your question seems to mistakenly refer to the list returned by func(2) as the list returned by func(1).)

func(0) == []
func(1) == [func(0)] == [[]]
func(2) == [func(0), func(1)] == [[], [[]]]
func(3) == [func(0), func(1), func(2)] == [[] , [[]] , [[], [[]]]]
...
func(n) == [func(0), func(1), ..., func(n-1)]
  • Related