|
| 1 | +classTree: |
| 2 | +parent="" |
| 3 | +children= [] |
| 4 | +name="" |
| 5 | + |
| 6 | +def__init__(self,name,parent="",children=[]): |
| 7 | +self.name=name |
| 8 | +self.children= [childforchildinchildrenifisinstance(child,Tree)] |
| 9 | +self.parent=parent |
| 10 | + |
| 11 | +def__repr__(self): |
| 12 | +returnself.name |
| 13 | + |
| 14 | +defadd_child(self,child): |
| 15 | +ifisinstance(child,Tree): |
| 16 | +self.children.append(child) |
| 17 | + |
| 18 | +defcount_children(self): |
| 19 | +returnlen(self.children) |
| 20 | + |
| 21 | +defcount_descendants(self): |
| 22 | +returnlen(self.children)+sum( |
| 23 | + [child.count_descendants()forchildinself.children] |
| 24 | + ) |
| 25 | + |
| 26 | +defget_descendants(self): |
| 27 | +returnself.children+ [child.get_descendants()forchildinself.children] |
| 28 | + |
| 29 | +defget_ancestors(self): |
| 30 | +ifself.parent=="": |
| 31 | +return [] |
| 32 | +else: |
| 33 | +result=self.parent.get_ancestors() |
| 34 | +result.insert(0,self.parent) |
| 35 | +returnresult |
| 36 | + |
| 37 | +defget_common_ancestor(self,other): |
| 38 | +my_parents= [self]+self.get_ancestors() |
| 39 | +his_parents= [other]+other.get_ancestors() |
| 40 | +common= [xforxinmy_parentsifxinhis_parents] |
| 41 | +ifnotcommon: |
| 42 | +returnNone |
| 43 | +returncommon[0] |
| 44 | + |
| 45 | +defget_degree_of_separation(self,other): |
| 46 | +my_parents= [self]+self.get_ancestors() |
| 47 | +his_parents= [other]+other.get_ancestors() |
| 48 | +common=self.get_common_ancestor(other) |
| 49 | +returnmy_parents.index(common)+his_parents.index(common) |