Show More
@@ -22,7 +22,24 from IPython.parallel.util import disambiguate_url | |||||
22 | #---------------------------------------------------------------------------- |
|
22 | #---------------------------------------------------------------------------- | |
23 |
|
23 | |||
24 | def bintree(ids, parent=None): |
|
24 | def bintree(ids, parent=None): | |
25 |
"""construct {child:parent} dict representation of a binary tree |
|
25 | """construct {child:parent} dict representation of a binary tree | |
|
26 | ||||
|
27 | keys are the nodes in the tree, and values are the parent of each node. | |||
|
28 | ||||
|
29 | The root node has parent `parent`, default: None. | |||
|
30 | ||||
|
31 | >>> tree = bintree(range(7)) | |||
|
32 | >>> tree | |||
|
33 | {0: None, 1: 0, 2: 1, 3: 1, 4: 0, 5: 4, 6: 4} | |||
|
34 | >>> print_bintree(tree) | |||
|
35 | 0 | |||
|
36 | 1 | |||
|
37 | 2 | |||
|
38 | 3 | |||
|
39 | 4 | |||
|
40 | 5 | |||
|
41 | 6 | |||
|
42 | """ | |||
26 | parents = {} |
|
43 | parents = {} | |
27 | n = len(ids) |
|
44 | n = len(ids) | |
28 | if n == 0: |
|
45 | if n == 0: | |
@@ -41,7 +58,17 def bintree(ids, parent=None): | |||||
41 | return parents |
|
58 | return parents | |
42 |
|
59 | |||
43 | def reverse_bintree(parents): |
|
60 | def reverse_bintree(parents): | |
44 |
"""construct {parent:[children]} dict from {child:parent} |
|
61 | """construct {parent:[children]} dict from {child:parent} | |
|
62 | ||||
|
63 | keys are the nodes in the tree, and values are the lists of children | |||
|
64 | of that node in the tree. | |||
|
65 | ||||
|
66 | reverse_tree[None] is the root node | |||
|
67 | ||||
|
68 | >>> tree = bintree(range(7)) | |||
|
69 | >>> reverse_bintree(tree) | |||
|
70 | {None: 0, 0: [1, 4], 4: [5, 6], 1: [2, 3]} | |||
|
71 | """ | |||
45 | children = {} |
|
72 | children = {} | |
46 | for child,parent in parents.iteritems(): |
|
73 | for child,parent in parents.iteritems(): | |
47 | if parent is None: |
|
74 | if parent is None: |
General Comments 0
You need to be logged in to leave comments.
Login now