[2021 spring] CS61A Lab 6: Nonlocal, Mutability, Iterators and Generators

lab06: https://inst.eecs.berkeley.edu/~cs61a/sp21/lab/lab06/#topics

Q1: WWPD: Nonlocal Quiz (Nonlocal WWPD)

parent frame中的变量x可以在sub frame中使用,但是不能修改,nonlocal x后,可以修改。注意:如果x为列表,可以进行append操作。

Q2: List-Mutation (Mutability)

注意:切片产生了新的列表

Q3: Insert Items (Mutability)

修改、返回原列表
注意:entry等于elem时,需要跳过这个已经添加到lst中的elem。

def insert_items(lst, entry, elem):
    """Inserts elem into lst after each occurence of entry and then returns lst.
    
    >>> test_lst = [1, 5, 8, 5, 2, 3]
    >>> new_lst = insert_items(test_lst, 5, 7)
    >>> new_lst
    [1, 5, 7, 8, 5, 7, 2, 3]
    >>> large_lst = [1, 4, 8]
    >>> large_lst2 = insert_items(large_lst, 4, 4)
    >>> large_lst2
    [1, 4, 4, 8]
    >>> large_lst3 = insert_items(large_lst2, 4, 6)
    >>> large_lst3
    [1, 4, 6, 4, 6, 8]
    >>> large_lst3 is large_lst
    True
    """
    "*** YOUR CODE HERE ***"
    i = 0
    while i < len(lst):
        if lst[i] == entry:
            lst.insert(i + 1, elem)
            if elem == entry:
                i += 1
        i += 1
    return lst

Q4: Scale (Iterators and Generators)

每次返回yield后的值,类似return

def scale(it, multiplier):
    """Yield elements of the iterable it multiplied by a number multiplier.

    >>> m = scale([1, 5, 2], 5)
    >>> type(m)
    <class 'generator'>
    >>> list(m)
    [5, 25, 10]

    >>> m = scale(naturals(), 2)
    >>> [next(m) for _ in range(5)]
    [2, 4, 6, 8, 10]
    """
    "*** YOUR CODE HERE ***"
    for i in it:
        yield i * multiplier

Q5: Hailstone

注意最后的1。

def hailstone(n):
    """Yields the elements of the hailstone sequence starting at n.
    
    >>> for num in hailstone(10):
    ...     print(num)
    ...
    10
    5
    16
    8
    4
    2
    1
    """
    "*** YOUR CODE HERE ***"
    while n != 1:
        yield n
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
    yield 1
posted @ 2021-07-02 11:28  ikventure  阅读(2846)  评论(0编辑  收藏  举报