Lab06 of CS61A of UCB
作者:互联网
Mutability
Write a function which takes in a list
lst
, an argumententry
, and another argumentelem
. This function will check through each item inlst
to see if it is equal toentry
. Upon finding an item equal toentry
, the function should modify the list by placingelem
intolst
right after the item. At the end of the function, the modified list should be returned.See the doctests for examples on how this function is utilized.
Important: Use list mutation to modify the original list. No new lists should be created or returned.
Note: If the values passed into
entry
andelem
are equivalent, make sure you're not creating an infinitely long list while iterating through it. If you find that your code is taking more than a few seconds to run, the function may be in a loop of inserting new values.
注意我们不能 for
循环来一边遍历这个 list
一边进行修改, 我记得我之前在《Effective Python》看过这一点. 其实自己 debug 就可以发现, 因为一开始用 for i in range(len(lst))
的时候就固定了, 但其实你在 for
循环里面会插入新的值, 这个 list
其实是变得更长的(但是 i
还是在原来的范围里), 所以后面超过本来长度的元素就会看不到.
注意下面这个代码是错误的
标签:10,cnt,val,iter,CS61A,lst,UCB,Lab06,entry 来源: https://www.cnblogs.com/MartinLwx/p/15917193.html