CS61a 2021Fall discussion 5——additional practice
Q7: Perfectly Balanced
Part A: Implement sum_tree, which returns the sum of all the labels in tree t.
Part B: Implement balanced, which returns whether every branch of t has the same total sum and that the branches themselves are also balanced.
Challenge: Solve both of these parts with just 1 line of code each.
第二问还没实现一行解决
def sum_tree(t):
"""
Add all elements in a tree.
>>> t = tree(4, [tree(2, [tree(3)]), tree(6)])
>>> sum_tree(t)
15
"""
"*** YOUR CODE HERE ***"
return label(t) + sum([sum_tree(branch) for branch in branches(t)])
def balanced(t):
"""
Checks if each branch has same sum of all elements and
if each branch is balanced.
>>> t = tree(1, [tree(3), tree(1, [tree(2)]), tree(1, [tree(1), tree(1)])])
>>> balanced(t)
True
>>> t = tree(1, [t, tree(1)])
>>> balanced(t)
False
>>> t = tree(1, [tree(4), tree(1, [tree(2), tree(1)]), tree(1, [tree(3)])])
>>> balanced(t)
False
"""
"*** YOUR CODE HERE ***"
sum_branches = [sum_tree(branch) for branch in branches(t)]
if not is_leaf(t) and sum_branches.count(sum_branches[0]) != len(sum_branches):
return False
for branch in branches(t):
if not balanced(branch):
return False
return True
Q8: Hailstone Tree
We can represent the hailstone sequence as a tree in the figure below, showing the route different numbers take to reach 1. Remember that a hailstone sequence starts with a number n
, continuing to n/2
if n is even or 3n+1
if n
is odd, ending with 1. Write a function hailstone_tree(n, h)
which generates a tree of height h
, containing hailstone numbers that will reach n
.
Hint: A node of a hailstone tree will always have at least one, and at most two branches (which are also hailstone trees). Under what conditions do you add the second branch?
def hailstone_tree(n, h):
"""Generates a tree of hailstone numbers that will reach N, with height H.
>>> print_tree(hailstone_tree(1, 0))
1
>>> print_tree(hailstone_tree(1, 4))
1
2
4
8
16
>>> print_tree(hailstone_tree(8, 3))
8
16
32
64
5
10
"""
if h == 0:
return tree(n)
branches = [hailstone_tree(2 * n, h - 1)] # 得写成列表形式后面才方便加
# 注意下一项不能是1
if (n - 1) % 3 == 0 and (n - 1) // 3 % 2 == 1 and (n - 1) // 3 != 1:
branches += [hailstone_tree((n - 1) // 3, h - 1)]
return tree(n, branches)
def print_tree(t):
def helper(i, t):
print(" " * i + str(label(t)))
for b in branches(t):
helper(i + 1, b)
helper(0, t)