-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtrees.py
More file actions
56 lines (48 loc) · 1.27 KB
/
trees.py
File metadata and controls
56 lines (48 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Tree:
"""
Binary tree.
>>> t = Tree(Tree("a", "b"), Tree("c", "d"))
>>> t.right.left
'c'
"""
[1, 1, 2, 6, 24, 120]
def __init__(self, left, right):
self.left = left
self.right = right
class Tree:
"""
Multiway tree class.
>>> t = Tree(Tree("a", Tree("b", Tree("c", Tree("d")))))
>>> t.kids.next.next.val
'c'
"""
def __init__(self, kids, next=None):
self.kids = self.val = kids
self.next = next
class Bunch(dict):
"""
The Bunch pattern.
>>> x = Bunch(name="Jayne Cobb", position="Public Relations")
>>> x.name
'Jayne Cobb'
Second, by subclassing dict, you get lots of functionality for free, such as iterating over the keys/attributes
or easily checking whether an attribute is present. Here’s an example:
>>> T = Bunch
>>> t = T(left=T(left="a", right="b"), right=T(left="c"))
>>> t.left
{'right': 'b', 'left': 'a'}
>>> t.left.right
'b'
>>> t['left']['right']
'b'
>>> "left" in t.right
True
>>> "right" in t.right
False
"""
def __init__(self, *args, **kwds):
super(Bunch, self).__init__(*args, **kwds)
self.__dict__ = self
if __name__ == "__main__":
import doctest
doctest.testmod()