设计实验以验证get item和set item是否为字典的O(1)O(1)

时间:2017-09-29 03:39:30

标签: python

所以我正在尝试编写一个代码来验证获取项目和设置项目是否为O(1)用于Python中的字典,但我得到以下错误(代码低于错误),请尽可能地帮助我没有看到语法有什么问题:

C:\Python27\python.exe "D:/MyPC/Python/python learning/review/2_11_Programming_Assignment"
Traceback (most recent call last):
  File "D:/MyPC/Python/python learning/review/2_11_Programming_Assignment", line 25, in <module>
    GetItem2 = timeit.Timer("aDict.get(newItem)",  "from__main__ import aDict")
  File "C:\Python27\lib\timeit.py", line 128, in __init__
    compile(setup, dummy_src_name, "exec")
  File "<timeit-src>", line 1
    from__main__ import aDict
                      ^
SyntaxError: invalid syntax

我的代码

import timeit
import random

GetItem1 = timeit.Timer("aDict.get(someitem)","from __main__ import aDict")
GetItem2 = timeit.Timer("aDict.get(newItem)",  "from__main__ import aDict")
GetItem3 = timeit.Timer("aDict.get(Itemfive)", "from__main__ import aDict")

SetItem1 = timeit.Timer("aDict.set(someItem)", "from __main__ import aDict")
SetItem2 = timeit.Timer("aDict.set(newItem)", "from __main__ import aDict")
SetItem3 = timeit.Timer("aDict.set(Itemfive)", "from __main__ import aDict")

aDict = {'someItem': 2, 'otherItem': 20,'newItem': 400, 'nextItem': 2000, 
'Itemfive': 900}

print "GetItem1 : %s " % (GetItem1.timeit(100)), "millseconds"
print "GetItem1 : %s " % (GetItem2.timeit(100)), "millseconds"
print "GetItem1 : %s " % (GetItem3.timeit(100)), "millseconds"

print "SetItem1 : %s " % (SetItem1.timeit(100)), "millseconds"
print "SetItem1 : %s " % (SetItem2.timeit(100)), "millseconds"
print "SetItem1 : %s " % (SetItem3.timeit(100)), "millseconds"

0 个答案:

没有答案