|
| 1 | +class Tree: |
| 2 | + parent = "" |
| 3 | + children = [] |
| 4 | + name = "" |
| 5 | + |
| 6 | + def __init__(self, name, parent="", children=[]): |
| 7 | + self.name = name |
| 8 | + self.children = [child for child in children if isinstance(child, Tree)] |
| 9 | + self.parent = parent |
| 10 | + |
| 11 | + def __repr__(self): |
| 12 | + return self.name |
| 13 | + |
| 14 | + def add_child(self, child): |
| 15 | + if isinstance(child, Tree): |
| 16 | + self.children.append(child) |
| 17 | + |
| 18 | + def count_children(self): |
| 19 | + return len(self.children) |
| 20 | + |
| 21 | + def count_descendants(self): |
| 22 | + return len(self.children) + sum( |
| 23 | + [child.count_descendants() for child in self.children] |
| 24 | + ) |
| 25 | + |
| 26 | + def get_descendants(self): |
| 27 | + return self.children + [child.get_descendants() for child in self.children] |
| 28 | + |
| 29 | + def get_ancestors(self): |
| 30 | + if self.parent == "": |
| 31 | + return [] |
| 32 | + else: |
| 33 | + result = self.parent.get_ancestors() |
| 34 | + result.insert(0, self.parent) |
| 35 | + return result |
| 36 | + |
| 37 | + def get_common_ancestor(self, other): |
| 38 | + my_parents = [self] + self.get_ancestors() |
| 39 | + his_parents = [other] + other.get_ancestors() |
| 40 | + common = [x for x in my_parents if x in his_parents] |
| 41 | + if not common: |
| 42 | + return None |
| 43 | + return common[0] |
| 44 | + |
| 45 | + def get_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 | + return my_parents.index(common) + his_parents.index(common) |
0 commit comments