Jose
Jose

Reputation: 21

Python Recursive Function from a 2 column Dataframe

I have the table below that I read into a dataFrame:

n,next_n
1,2
1,3
1,6
2,4
2,8
3,5
3,9
4,7
9,10

My recursive function should return multiple lists of numbers through the end.
For example if I select to see all the values associated with 9, I should get a list that reads [9,10].
Another example:
4 should yield [4,7]

3 yields two lists
[3,5]
[3,9,10]

def recursivenum(df,n):
    indices = list()
    
    indices.append(n)

    x = df[df['n'] == n].next_n

    if len(x) > 0:
        for p1 in df[df['n'] == n].next_n:
            indices  = indices + recursivenum(df,p1)

    elif len(x) == 0: #Base case - There are no other values        
        print(indices)
    
    return indices

When I run recursivenum(df,1)

I get
[7]
[8]
[5]
[10]
[6]
[1, 2, 4, 7, 8, 3, 5, 9, 10, 6]

Which is nothing compared to what I expect to see.


I expect to see five lists: [1,2,4,7]
[1,2,8]
[1,3,5]
[1,3,9,10]
[1,6]

Can someone point me in the right direction?

Upvotes: 2

Views: 341

Answers (2)

BENY
BENY

Reputation: 323226

This is more like a network problem , you would like to create the directed graph , then from the root (1) to the leaf (any value with level 0)

import networkx as nx
G=nx.from_pandas_edgelist(df,source='n',target='next_n', edge_attr=None, create_using=nx.DiGraph())
paths=[]
for node in G:
      if G.out_degree(node)==0: #it's a leaf
          paths.append(nx.shortest_path(G, 1, node))
          
paths
Out[42]: [[1, 6], [1, 2, 8], [1, 3, 5], [1, 2, 4, 7], [1, 3, 9, 10]]

Upvotes: 1

Lynnlo
Lynnlo

Reputation: 105

If the array consists of tuples, try using a for loop.

def recursivenum(df,n):
    indices = list()
    
    for x,y in df:
        if x == n:
            indices.append([x,y])
    
    return indices

Upvotes: 0

Related Questions