Home > Software design >  Recursive function to go through list of references to indices in same list
Recursive function to go through list of references to indices in same list

Time:11-19

I have this list:

[[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []]

It could be described as a list of references to other items in the same list, like this:

0 --> 1 2 3 4
1 --> 5
2 --> 6 7
3 --> 8
4 --> 9
5 --> 10 11
6 --> 12 13 14
7 --> 15 16
8 --> 15 16
9 --> 15 16
10 --> 17
11 --> 18
12 --> 19
13 --> 20
14 --> 21
15 --> 20
16 --> 21
17 --> None
18 --> None
19 --> None
20 --> None
21 --> None

So, from index 0 one can move to either 1, 2, 3 or 4. From 1 you can go to 5, and from 5 you can go to 10 etc. until you can't go any further (like when you reach index 17).

I'm trying to make a function that would return this when fed the above list:

[0,1,5,10,17]
[0,1,5,11,18]
[0,2,6,12,19]
[0,2,6,13,20]
[0,2,6,14,21]
[0,2,7,15,20]
[0,2,7,16,21]
[0,3,8,15,20]
[0,3,8,16,21]
[0,4,9,15,20]
[0,4,9,16,21]

Unfortunately, I just can't come up a solution.

I understand that this probably calls for a recursive function, but I'm getting so confused by it. Without actually knowing what I did, I managed to come up with this function:

def recurse_into(A,i):
    B = [i]
    for j in tree[i]:
        B  = recurse_into(A,j)
    return B

It returns this:

[0, 1, 5, 10, 17, 11, 18, 2, 6, 12, 19, 13, 20, 14, 21, 7, 15, 20, 16, 21, 3, 8, 15, 20, 16, 21, 4, 9, 15, 20, 16, 21]

From that I probably could come up with something that generates the wanted results, but I wonder how I could get the result I want directly from the recursive function.

I would very much appreciate some pointers or tips on how to achieve this.

Thanks!

CodePudding user response:

Here is my implementation of what I understood from my requirements


def dfs(graph, u, curr,res):
    c = curr  [u]
    if(len(graph[u]) == 0):
        res.append(c)
    for v in graph[u]:
        dfs(graph, v, c, res)
        
    
    
graph = [[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []]

u = 0
res = []
dfs(graph, u, [],res)

print(res)

So I'm doing a DFS here.

CodePudding user response:

tree = [[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []]

def recourse_into(i):
    R=[]
    if len(tree[i]) ==0 :
            return [[i]]
    for h in  tree[i]:
        t=recourse_into(h)
        for j in t :
            R.append([i] j)
    return R


print(recourse_into(0))
  • Related