-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.py
96 lines (67 loc) · 1.86 KB
/
tree.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 22:25:14 2021
@author: Joyce
"""
def tree(label, branches = []):
for branch in branches:
assert is_tree(branch), 'branches must be trees'
return [label] + list(branches)
def label(tree):
return tree[0]
def branches(tree):
return tree[1:]
def is_tree(tree):
if type(tree) != list or len(tree) < 1:
return False
for branch in branches(tree):
if not is_tree(branch):
return False
return True
def is_leaf(tree):
return not branches(tree)
def fib_tree(n):
if n <= 1:
return tree(n)
else:
left, right = fib_tree(n-2), fib_tree(n-1)
return tree(label(left) + label(right), [left,right])
def count_leaf(tree):
if is_leaf(tree):
return 1
else:
return sum(count_leaf(i) for i in branches(tree))
def increment_leaves(t):
"""Return a tree like t but with leaf labels inremented"""
if is_leaf(t):
return tree(label(t) + 1)
else:
bs = [increment_leaves(b) for b in branches(t)]
return tree(label(t), bs)
def increment(t):
"""Return a tree like t but with all labels incremented."""
return tree(label(t) + 1, [increment(b) for b in branches(t)])
def print_tree(t, indent = 0):
print(' ' * indent + str(label(t)))
for b in branches(t):
print_tree(b, indent + 1)
def fact(n):
if n == 0:
return 1
else:
return n * fact(n - 1)
def fact_times(n ,k):
"""Return k * n * (n-1) * ...* 1"""
if n == 0:
return k
else:
return fact_times(n - 1, k * n)
def fact_new(n):
return fact_times(n, 1)
def print_sums(t, so_far):
so_far = so_far + label(t)
if is_leaf(t):
print(so_far)
else:
for branch in branches(t):
print_sums(branch, so_far)