Skip to content

Commit 0f35a02

Browse files
committed
Added Tree library
1 parent 4efbb88 commit 0f35a02

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

2019/tree.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy