>>> paragraph = "five hundred to one hundred words separated by spaces"
>>> array_of_strings = set(['hundred', 'spaces', ]) # make a set..
>>> print set(paragraph.split()).intersection(array_of_strings)
set(['hundred', 'spaces'])
import timeit
s = """paragraph = "five hundred to one hundred words separated by spaces"
array_of_strings = set(['hundred', 'spaces', ]) # make a set..
set(paragraph.split()).intersection(array_of_strings)
"""
t = timeit.Timer(stmt=s)
print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
1
如果使用列表,请先对其进行排序并使用二进制搜索 .
但是使用字典可能会更好;)
import time
def timeo(fun, n=1000):
def void( ): pass
start = time.clock( )
for i in range(n): void( )
stend = time.clock( )
overhead = stend - start
start = time.clock( )
for i in range(n): fun( )
stend = time.clock( )
fulltime = stend-start
return fun.__name__, fulltime-overhead
for f in solution1, solution2, solution3:
print "%s: %.2f" % timeo(f)
2 回答
我会将你的5500个字符串数组转换为一个集合,并使用一个集合交集 .
这是你如何计时的 .
阅读timeit模块 . 这是另一个教程:http://diveintopython.net/performance_tuning/timeit.html
如果使用列表,请先对其进行排序并使用二进制搜索 .
但是使用字典可能会更好;)