标签:topic int 需要 while == header 修改 append lse
lab06: https://inst.eecs.berkeley.edu/~cs61a/sp21/lab/lab06/#topics
parent frame中的变量x可以在sub frame中使用,但是不能修改,nonlocal x后,可以修改。注意:如果x为列表,可以进行append操作。
注意:切片产生了新的列表
修改、返回原列表
注意: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
每次返回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
注意最后的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
[2021 spring] CS61A Lab 6: Nonlocal, Mutability, Iterators and Generators
标签:topic int 需要 while == header 修改 append lse
原文地址:https://www.cnblogs.com/ikventure/p/14961532.html