2015-06-06 54 views
0

這裏,德爾操作員定時:時機需要多長時間做在運營商

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)) 

這一次,它選擇的時機需要多長時間做在運營商,而不是運營商德爾。哪些代碼需要更改和添加?

+0

與dict查找相比,構造dict的時間有點誤導,因爲構建每個測試字符串所花費的時間是顯着的。要看到這個,從inx(x,n)'中的每一行中刪除'in x'。只調用'inx()'函數和構造字符串的結果時間大約是進行完整測試的時間的50%。 –

+0

嗯,我可以看到,但是它與計時運算符有關嗎? – devacris14

+0

是的,沒有。 :)上面的代碼肯定表明,「in」在字典上比在相同大小的列表上快得多。但是它報告的時間並不是僅僅計算'in'操作 - 這些時間還包括調用'inx()'函數本身以及構建4個字符串所需的時間。而且這些東西的耗時與在字典中進行實際的「內部」操作大致相同。因此,代碼打印的數字不應該被視爲精確地顯示列表中的「in」與字典之間的相對速度差異。 –

回答

0

您需要分別爲列表和字典實現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 delx(x, n): # do in front, middle, end, and not found 
    if x is list: 
     del x[0] # deleting first element in list 
     del x[(n-1)//2] # middle element delete n-1 because 0-th element is already deleted 
     del x[-1] # last element delete 
    if x is dict: 
     del x[str(0)] # deleting first element in dict 
     del x[str((n-1)//2)] # deleting middle element from dict 
     del x[str((n-2)-1)] # last element delete n-2 because 0-th and middle element is already deleted 
     # str("a") in x # not in it 

timeList = Timer(
    "delx(x,n)", 
    "from __main__ import n,build_list,delx; x = build_list(n)") 

timeDict = Timer(
    "delx(x,n)", 
    "from __main__ import n,build_dict,delx; 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)) 
+0

似乎運行正常。我認爲這與del x有關。雖然並不特別是100%。非常感謝你幫助我,k4vin。 – devacris14