一、Add_trees in lab05
题目:
Define the function
add_trees
, which takes in two trees and returns a new tree where each corresponding node from the first tree is added with the node from the second tree. If a node at any particular position is present in one tree but not the other, it should be present in the new tree as well.Hint: You may want to use the built-in zip function to iterate over multiple sequences at once.
Note: If you feel that this one's a lot harder than the previous tree problems, that's totally fine! This is a pretty difficult problem, but you can do it! Talk about it with other students, and come back to it if you need to.
def add_trees(t1, t2): """ >>> numbers = tree(1, ... [tree(2, ... [tree(3), ... tree(4)]), ... tree(5, ... [tree(6, ... [tree(7)]), ... tree(8)])]) >>> print_tree(add_trees(numbers, numbers)) 2 4 6 8 10 12 14 16 >>> print_tree(add_trees(tree(2), tree(3, [tree(4), tree(5)]))) 5 4 5 >>> print_tree(add_trees(tree(2, [tree(3)]), tree(2, [tree(3), tree(4)]))) 4 6 4 >>> print_tree(add_trees(tree(2, [tree(3, [tree(4), tree(5)])]), \ tree(2, [tree(3, [tree(4)]), tree(5)]))) 4 6 8 5 5 """ "*** YOUR CODE HERE ***"
代码:
def add_trees(t1, t2):
if not t1:
return t2
if not t2:
return t1
label_sum = label(t1) + label(t2)
new_branches = []
print('DEBUG:', zip(branches(t1), branches(t2)))
for branch1, branch2 in zip(branches(t1), branches(t2)):
new_branches.append(add_trees(branch1, branch2))
print('DEBUG:', 'nb',new_branches)
remaining_branches = branches(t1)[len(new_branches):] + branches(t2)[len(new_branches):]
new_branches += remaining_branches
return tree(label_sum, new_branches)
二、prune_binary in disc05
题目:
代码:
def prune_binary(t, nums):
if is_leaf(t):
if label(t) in nums:
return t
return None
else:
next_valid_nums = [i[1:] for i in nums if i[0] == label(t)]
new_branches = []
for b in branches(t):
pruned_branch = prune_binary(b, next_valid_nums)
if pruned_branch is not None:
new_branches = new_branches + [pruned_branch]
if not new_branches:
return None
return tree(label(t),new_branches)
做题的时候一直有一种很模糊的感觉,主要是都涉及到把一棵树添加到另一棵树的分支上去,或者说涉及到树的加法,比如第一题,如果两棵树的某一级的分支数不一样,就要把遍历完做了加法分支和多出来的分支加起来,第二题也涉及到加法,并且还是在一个for循环里,做这两题的时候我都很迷糊,不知道分支加起来是个什么东西,为什么就能直接用+号,也很纠结要不要我要不要套个[],。如果是让我来的话,可能我会专门写一个树的加法函数,抽象出来。
另外的话,就是zip可以用来同时iterate多个iterations,然后就是对序列的操作,比如
s == '123'
如果s[3]会报错,但s[3:]就不会报错,会返回一个空的对应的序列。