python find root/parent based on list of tuples -
suppose have list of tuples in store keys (strings):
l=[ (a,b), (b,c), (c,d), (d,e), (e,f), (w,x), (w,t), (t,q), (q,r), (q,u), ]
how can find relations (especially head) between tuples in list, eg:
a<-b<-c<-d<-e<-f w<(-x,t-<q-<(r,u))
so know f
grand grand grand grand child of a
?
regards js.
we'll have dictionary mapping names tonode
s, , build nodes trees.
from collections import defaultdict class node: def __init__(self): children = [] def add_child(self, child): self.children.append(child) def ancestor_of(self, descendant): if self == descendant: return [self] child in children: c=child.ancestor_of(descendant) if c: return [self, *c] return none node_dict = defaultdict(node) fst, snd in l: #assuming , b strings d[fst].add_child(d[snd]) #query trees using ancestor_of
Comments
Post a Comment