Problem 9: Insert (100pts)
Problem
Write a function
insert_itemswhich takes as input a listlst, an argumententry, and another argumentelem.This function will check through each item present in
lstto see if it is equivalent withentry. Upon finding an equivalent entry, the function should modify the list by placingeleminto the list right after the found entry.At the ending of the function, the modified list should be returned.
See the doctests for examples about the usage of this function. Use list mutation to modify the original list, no new lists should be created or returned.
Be careful in situations where the values passed into entry and elem are equivalent, so as not to create an infinitely long list while iterating through it. If you find that your code is taking more than a few seconds to run, it is most likely that the function is in a loop of inserting new values.
编写一个函数 insert_items,它接受一个列表 lst、一个参数 entry 和另一个参数 elem 作为输入。
这个函数将检查 lst 中存在的每个项目,看它是否与 entry 相等。
一旦找到相等的条目,函数应该通过在找到的条目之后立即将 elem 放入列表中来修改该列表。
在函数结束时,应该返回修改后的列表。
请参阅文档测试(doctests)以获取该函数用法的示例。 请使用列表修改(list mutation)来修改原始列表,不应创建或返回新列表。
请特别注意 entry 和 elem 传入的值相等的情况,以免在遍历列表时创建无限长的列表。
如果您发现您的代码运行时间超过几秒,那很可能是您的函数陷入了插入新值的循环中。
def insert_items(lst, entry, elem):
"""
>>> 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 ***"
Hints
Hint: You may use the
lst.insert(ind, obj)to insert an elementobjto a position indexed byind. Search the internet for more information about its usage. Here is just a reference from Python Documentation.
- 您可以使用
lst.insert(ind, obj)将元素obj插入到由ind索引指定的位置。请在互联网上搜索有关其用法的更多信息。 - 这是 Python 文档中的一个参考。
Solutions
遍历 lst,遇到 entry 时 insert。
def insert_items(lst, entry, elem):
i = 0
while i < len(lst):
if lst[i] == entry:
i += 1
lst.insert(i, item)
i += 1
return lst
先创建新的列表,然后用切片复制,达到返回原有列表的目的
def insert_items(lst, entry, elem):
new = [j for i in lst for j in ([i, elem] if i == entry else [i])]
lst[:] = new
return lst
压行(使用魔术方法返回 None 的特性)
def insert_items(lst, entry, elem):
return lst.__setitem__(slice(None), [j for i in lst for j in ([i, elem] if i == entry else [i])]) or lst