2021 fall lab8
阿新 • • 發佈:2022-04-09
網址 https://inst.eecs.berkeley.edu/~cs61a/fa21/lab/lab08/
problem1:
problem2:
def convert_link(link): """Takes a linked list and returns a Python list with the same elements. >>> link = Link(1, Link(2, Link(3, Link(4)))) >>> convert_link(link) [1, 2, 3, 4] >>> convert_link(Link.empty) [] """ "*** YOUR CODE HERE ***" ans = [] while link is not Link.empty: ans.append(link.first) link = link.rest return ans
problem3:
problem4:
def label_squarer(t): """Mutates a Tree t by squaring all its elements. >>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)]) >>> label_squarer(t) >>> t Tree(1, [Tree(9, [Tree(25)]), Tree(49)]) """ "*** YOUR CODE HERE ***" t.label = t.label * t.label for i in t.branches: label_squarer(i)
problem5:
def cumulative_mul(t): """Mutates t so that each node's label becomes the product of all labels in the corresponding subtree rooted at t. >>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)]) >>> cumulative_mul(t) >>> t Tree(105, [Tree(15, [Tree(5)]), Tree(7)]) """ "*** YOUR CODE HERE ***" for i in t.branches: cumulative_mul(i) t.label = t.label * i.label
problem6:
先從子樹開始加v,然後往上,這樣就不會使得v被認為是leaf
def add_d_leaves(t, v):
"""Add d leaves containing v to each node at every depth d.
"*** YOUR CODE HERE ***"
def depth(t, v, d):
for i in t.branches:
depth(i, v, d+1)
for _ in range(d):
t.branches.append(Tree(v))
return depth(t, v, 0)
problem7:
def every_other(s):
"""Mutates a linked list so that all the odd-indiced elements are removed
(using 0-based indexing).
>>> s = Link(1, Link(2, Link(3, Link(4))))
>>> every_other(s)
>>> s
Link(1, Link(3))
>>> odd_length = Link(5, Link(3, Link(1)))
>>> every_other(odd_length)
>>> odd_length
Link(5, Link(1))
>>> singleton = Link(4)
>>> every_other(singleton)
>>> singleton
Link(4)
"""
"*** YOUR CODE HERE ***"
while s != Link.empty:
if s.rest:
s.rest = s.rest.rest
s = s.rest
else:
s = s.rest
problem8:
從上往下,可以最大減少執行時間
def prune_small(t, n):
"""Prune the tree mutatively, keeping only the n branches
of each node with the smallest label.
>>> t1 = Tree(6)
>>> prune_small(t1, 2)
>>> t1
Tree(6)
>>> t2 = Tree(6, [Tree(3), Tree(4)])
>>> prune_small(t2, 1)
>>> t2
Tree(6, [Tree(3)])
>>> t3 = Tree(6, [Tree(1), Tree(3, [Tree(1), Tree(2), Tree(3)]), Tree(5, [Tree(3), Tree(4)])])
>>> prune_small(t3, 2)
>>> t3
Tree(6, [Tree(1), Tree(3, [Tree(1), Tree(2)])])
"""
while len(t.branches) > n:
largest = max(t.branches, key=lambda x : x.label)
t.branches.remove(largest)
for __ in t.branches:
prune_small(__, n)