这里,del操作符是定时的:
from timeit import Timer
def build_list(n):
return list(range(n)) # create list of 1 to n
def build_dict(n): # build dict = { 0:"0", 1:"1", 2:"2", ... n:"n" }
return {i: str(i) for i in range(n)} # from last listing in this chapter
def inx(x,n): # do in front, middle, end, and not found
str(0) in x
str(n//2) in x
str(n-1) in x
str("a") in x # not in it
timeList = Timer(
"inx(x,n)",
"from __main__ import n,build_list,inx; x = build_list(n)")
timeDict = Timer(
"inx(x,n)",
"from __main__ import n,build_dict,inx; x = build_dict(n)")
# get min of 5 runs of 5
print("N", "\t", "List", "\t", "Dict")
for size in range(1000, 100000+1, 5000): # sizes to graph for n:
n = size
list_secs = timeList.repeat(5,5)
dict_sect = timeDict.repeat(5,5)
print(n, "\t", min(list_secs), "\t", min(dict_sect))
这一次,是计时执行in操作符而不是del操作符所需的时间。需要更改和添加哪些代码?你知道吗
您需要为list和dict分别实现del,因为list采用整数作为索引,并且您的字典具有字符串键。因为我们不能删除列表或dict中不存在的元素,所以我省略了该部分。你知道吗
相关问题 更多 >
编程相关推荐