Lab06 of CS61A of UCB

2022/2/21 6:27:54

本文主要是介绍Lab06 of CS61A of UCB,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Mutability


Write a function which takes in a list lst, an argument entry, and another argument elem. This function will check through each item in lst to see if it is equal to entry. Upon finding an item equal to entry, the function should modify the list by placing elem into lst 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 and elem 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 还是在原来的范围里), 所以后面超过本来长度的元素就会看不到.

注意下面这个代码是错误的



这篇关于Lab06 of CS61A of UCB的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程