Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0f35a02

Browse files
committed
Added Tree library
1 parent4efbb88 commit0f35a02

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+
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)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp