# [2021-Fall] Lab08 of CS61A of UCB

Write a function convert_link that takes in a linked list and returns the sequence as a Python list. You may assume that the input list is shallow; that is none of the elements is another linked list.

Try to find both an iterative and recursive solution for this problem!

def convert_link(link):
"""Takes a linked list and returns a Python list with the same elements.
"""
result = []
return result


def convert_link(link):
"""Takes a linked list and returns a Python list with the same elements.
"""
# recursive solution
return []
else:


## Trees

### Q4: Square

Write a function label_squarer that mutates a Tree with numerical labels so that each label is squared.

def label_squarer(t):
"""Mutates a Tree t by squaring all its elements.
"""
# base case
if t.is_leaf():
t.label = t.label ** 2

# check every branch
for b in t.branches:
t.label = t.label ** 2          # change the current node's label
label_squarer(b)                # change branches


### Q5: Cumulative Mul

Write a function cumulative_mul that mutates the Tree t so that each node's label becomes the product of its label and all labels in the subtrees rooted at the node.

base case 就是叶子结点, 此时返回叶子节点的 label. 递归分解问题就是遍历节点的每一个子树, 获得每个子节点返回值再乘以当前结点的 label.

def cumulative_mul(t):
"""Mutates t so that each node's label becomes the product of all labels in
"""
# base case
if t.is_leaf():
return t.label
# get all label value in subtree
vals = [cumulative_mul(b) for b in t.branches]

# calculate
t.label *= math.prod(vals)


Implement add_d_leaves, a function that takes in a Tree instance t and a number v.

We define the depth of a node in t to be the number of edges from the root to that node. The depth of root is therefore 0.

For each node in the tree, you should add d leaves to it, where d is the depth of the node. Every added leaf should have a label of v. If the node at this depth has existing branches, you should add these leaves to the end of that list of branches.

For example, you should be adding 1 leaf with label v to each node at depth 1, 2 leaves to each node at depth 2, and so on.

Here is an example of a tree t(shown on the left) and the result after add_d_leaves is applied with v as 5.

base case 就是在叶子结点, 我们根据它的高度增加子结点. 然后对于当前的节点, 我们需要对它的每个孩子节点重复这个步骤, 同时也要判断当前节点是否需要添加子节点

def add_d_leaves(t, v):
"""Add d leaves containing v to each node at every depth d.
"""
def helper(t, v, depth):
# base case
if t.is_leaf():
for i in range(depth):
t.branches.append(Tree(v))
return

# check every branch
for b in t.branches:
helper(b, v, depth + 1)

# check current node
for i in range(depth):
t.branches.append(Tree(v))

helper(t, v, 0)


## Optional Questions

### Q7: Every Other

Implement every_other, which takes a linked list s. It mutates s such that all of the odd-indexed elements (using 0-based indexing) are removed from the list. For example:

>>> s = Link('a', Link('b', Link('c', Link('d'))))
>>> every_other(s)
>>> s.first
'a'
>>> s.rest.first
'c'
True


If s contains fewer than two elements, s remains unchanged.

Do not return anything! every_other should mutate the original list.

def every_other(s):
"""Mutates a linked list so that all the odd-indiced elements are removed
"""
# if it contains fewer than 2, do nothing
return

last_pos, pos = s, s.rest
current_index = 1               # start from 2nd position
if current_index % 2 == 1:
last_pos.rest = pos.rest
last_pos = pos
pos = pos.rest
current_index += 1


### Q8: Prune Small

Complete the function prune_small that takes in a Tree t and a number n and prunes t mutatively. If t or any of its branches has more than n branches, the n branches with the smallest labels should be kept and any other branches should be pruned, or removed, from the tree.

def prune_small(t, n):
"""Prune the tree mutatively, keeping only the n branches
of each node with the smallest label.
"""
while len(t.branches) > n:
largest = max(t.branches, key=lambda x: x.label)
t.branches.remove(largest)

for b in t.branches:
prune_small(b, n)

posted @ 2022-02-25 11:15  MartinLwx  阅读(2116)  评论(0编辑  收藏  举报