[2021 Spring] CS61A Discussion 7: String Representation, Efficiency, Linked Lists, Mutable Trees

Discussion 7: https://inst.eecs.berkeley.edu/~cs61a/sp21/disc/disc07/

Representation - Repr and Str

Linked Lists

Q2: Sum Nums

while循环

def sum_nums(s):
    """
    >>> a = Link(1, Link(6, Link(7)))
    >>> sum_nums(a)
    14
    """
    "*** YOUR CODE HERE ***"
    a = 0
    while s:
        a += s.first
        s = s.rest
    return a

Q5: (Tutorial) Multiply Lnks

递归

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
    mul = 1
    for link in lst_of_lnks:
        if link is Link.empty:
            return Link.empty
        mul *= link.first
    next_link = [link.rest for link in lst_of_lnks]
    return Link(mul, multiply_lnks(next_link))

Q6: (Tutorial) Flip Two

链表成对节点交换

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 ***"
    while s and s.rest:
        tmp = s.rest.first
        s.rest.first = s.first
        s.first = tmp
        s = s.rest.rest

Trees

Q7: Make Even

子树迭代

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 b in t.branches:
        make_even(b)
posted @ 2021-07-14 23:32  ikventure  阅读(478)  评论(0编辑  收藏  举报