2021 fall cs61a dis08
作者:互联网
网址 https://inst.eecs.berkeley.edu/~cs61a/fa21/disc/disc08/
problem1:
problem2:
problem3:
递归
def sum_nums(s):
"""
>>> a = Link(1, Link(6, Link(7)))
>>> sum_nums(a)
14
"""
"*** YOUR CODE HERE ***"
if s is Link.empty:
return 0
return s.first + sum_nums(s.rest)
problem4:
这个也是用递归,因为不好判断哪一个链表最短,所以直接迭代比较麻烦
def multiply_lnks(lst_of_lnks):
"""
>>> a = Link(2, Link(3, Link(5)))
>>> b = Link(6, Link(4, Link(2)))
>>> c = Link(4, Link(1, Link(0, Link(2))))
>>> p = multiply_lnks([a, b, c])
>>> p.first
48
>>> p.rest.first
12
>>> p.rest.rest.rest is Link.empty
True
"""
# Implementation Note: you might not need all lines in this skeleton code
product = 1
for lnk in lst_of_lnks:
if lnk is Link.empty:
return Link.empty
product *= lnk.first
lst_of_lnks_rset = [lnk.rest for lnk in lst_of_lnks]
return Link(product, multiply_lnks(lst_of_lnks_rset))
problem5:
递归和迭代
def flip_two(s):
"""
>>> one_lnk = Link(1)
>>> flip_two(one_lnk)
>>> one_lnk
Link(1)
>>> lnk = Link(1, Link(2, Link(3, Link(4, Link(5)))))
>>> flip_two(lnk)
>>> lnk
Link(2, Link(1, Link(4, Link(3, Link(5)))))
"""
"*** YOUR CODE HERE ***"
#if s is Link.empty or s.rest is Link.empty:
# return
#tmp = s.rest.first
#s.rest.first = s.first
#s.first = tmp
#flip_two(s.rest.rest)
# For an extra challenge, try writing out an iterative approach as well below!
"*** YOUR CODE HERE ***"
while s is not Link.empty and s.rest is not Link.empty:
tmp = s.rest.first
s.rest.first = s.first
s.first = tmp
s = s.rest.rest
problem6:
def make_even(t):
"""
>>> t = Tree(1, [Tree(2, [Tree(3)]), Tree(4), Tree(5)])
>>> make_even(t)
>>> t.label
2
>>> t.branches[0].branches[0].label
4
"""
"*** YOUR CODE HERE ***"
if t.label % 2 == 1:
t.label += 1
for i in t.branches:
make_even(i)
problem7:
def leaves(t):
"""Returns a list of all the labels of the leaf nodes of the Tree t.
>>> leaves(Tree(1))
[1]
>>> leaves(Tree(1, [Tree(2, [Tree(3)]), Tree(4)]))
[3, 4]
"""
"*** YOUR CODE HERE ***"
ans = []
if t.is_leaf():
return [t.label]
for i in t.branches:
ans += leaves(i)
return ans
problem8:
def find_paths(t, entry):
"""
>>> tree_ex = Tree(2, [Tree(7, [Tree(3), Tree(6, [Tree(5), Tree(11)])]), Tree(1, [Tree(5)])])
>>> find_paths(tree_ex, 5)
[[2, 7, 6, 5], [2, 1, 5]]
>>> find_paths(tree_ex, 12)
[]
"""
paths = []
if t.label == entry:
[[t.label]]
for i in t.branches:
path = find_paths(i,entry)
for j in path:
j = [t.label] + j
paths.append(j)
return paths
标签:return,Tree,rest,cs61a,dis08,Link,2021,lnk,first 来源: https://www.cnblogs.com/echoT/p/16127141.html