0

I am really a newbie in python. Could you please help in the following problem

I have the following table:

Parent  Child   value 1 Value 2

a0      b1      0.2         5

b5      c1      0.3         2

a0      b2      0.5         6

a1      b3      0.6         3

a1      b4      0.7         58

a2      b5      0.5         63

f0      a0      0.6         9

f0      a1      0.8         5

f0      a2      0.5         5

a0      b0      0.2         6

b5      c0      0.6         4

I need to do recursive parent child relationship and need to find all parents with a given child. However, I also need to multiply the values with each other for a give parent and child combination.

Expected output

Root    Parent  Child   Path              Value 3 

f0      b5      c1      f0/a2/b5/c1       0.5 * 0.5 * 0.3  (f0->a2 * a2->b5 * b5->c1)

f0      a0      b0      f0/a0/b0          0.6 * 0.2  (f0->a0 * a0->b0)

f0      a1      b4      f0/a1/b4          ..and so on

f0      a1      b3      f0/a1/b3    

f0      b5      c0      f0/a2/b5/c0 

f0      a0      b2      f0/a0/b2    

f0      a0      b1      f0/a0/b1

I am using the following code which works perfectly fine. I got this code from this site only. However, I am not able to figure out how to get the value 3 by multiplying the value 1 as a recourse through the path.

parents = set() children = {} for c,p in ancestry:
    parents.add(p)
    children[c] = p

def ancestors(p):
    return (ancestors(children[p]) if p in children else []) + [p] 

for k in (set(children.keys()) - parents): print ('/'.join(ancestors(k)))

any help is greatly appreciated.

Michael Butscher
  • 10,028
  • 4
  • 24
  • 25

1 Answers1

0

I am not sure of how to solve this issue using recursion, but below solution may work for you. As you already pulled leaf nodes and traversing to parent node, I added a tuple "childvalues" to track the parent and it's value for each child. Then I traversed upward to get each parent one by one along with multiplication result

def ancestor(child):
    child_weight = 1
    childpath = "/" + child
    while (child in childvalues):
        pathValue = childvalues[child][1]
        child_weight = child_weight * pathValue
        child = childvalues[child][0]
        childpath = childpath + "/" + child
    return (childpath, child_weight)
ancestry = [
    ('b1', 'a0', 0.1),
    ('c1', 'b5', 0.2),
    ('b2', 'a0', 0.3),
    ('b3', 'a1', 0.4),
    ('b4', 'a1', 0.5),
    ('b5', 'a2', 0.6),
    ('a0', 'f0', 0.7),
    ('a1', 'f0', 0.8),
    ('a2', 'f0', 0.9),
    ('b0', 'a0', 0.11),
    ('c0', 'b5', 0.12),
]
parents = set()
childvalues = {}
for child, parent, value in ancestry:
    parents.add(parent)
    childvalues[child] = (parent, value)
for leaf_node in (set(childvalues.keys()) - parents):
    print(ancestor(leaf_node))
Manash Deb
  • 261
  • 4
  • 5