CS61a 2021Fall ディスカッション 5——追加練習

CS61a 2021Fall ディスカッション 5——追加練習

Q7: 完璧なバランス

パート A:ツリー t のすべてのラベルの合計を返す sum_tree を実装します。

パート B: t のすべてのブランチの総和が同じかどうか、およびブランチ自体もバランスが取れているかどうかを返す、balanced を実装します。

課題:これらの両方の部分をそれぞれ 1 行のコードで解決する.
2 番目の質問は 1 行では解決されていません

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: 雹の木

雹のシーケンスを下の図のツリーとして表すことができ、さまざまな数字が 1 に到達するまでのルートを示しています。雹のシーケンスは数字 で始まり、n が偶数またはn奇数n/2の場合に続き、1 で終わることに3n+1注意してください。到達する雹の数を含む、高さの木を生成するn関数hailstone_tree(n, h)hn

ヒント:ヘイルストーン ツリーのノードには、常に少なくとも 1 つ、多くても 2 つの枝 (ヘイルストーン ツリーでもあります) があります。2 番目のブランチを追加する条件は何ですか?

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)

おすすめ

転載: blog.csdn.net/weixin_42236469/article/details/122689677