【问题标题】:Python fast contains methodPython 快速包含方法
【发布时间】:2013-11-26 20:02:08
【问题描述】:
如果我在 Python 中有一个字典,那么搜索一个不存在的键的时间复杂度是多少?
d = {}
if key not in d:
print "Key not found!"
in 是否对键数组进行线性搜索?
是否存在在数据结构中搜索特定字符串的 O(1) 实现?对于contains() 方法有效。
【问题讨论】:
标签:
python
dictionary
key
contains
【解决方案1】:
它必须为字典摊销O(1),因为最后in 运算符只是执行成员查找,not 没有额外的开销。请查看此answer,了解有关字典情况下in 运算符时间复杂度的更多详细信息。
【解决方案2】:
它的 O(1) 字典被实现为一个哈希表,并且在做哈希表查找
【解决方案3】:
字典通常查找时间为 O(1)。
拥有一个为其哈希返回常量的类是完全可以接受的,但这会降低字典查找的线性度。
例如。
class dumbint(int):
def __hash__(self):
return 0
$ python -m timeit -s 'class dumbint(int):__hash__ = lambda x:0' -s 'd={dumbint(i):i for i in range(100)}' 'dumbint(-1) in d'
100000 loops, best of 3: 3.64 usec per loop
$ python -m timeit -s 'class dumbint(int):__hash__ = lambda x:0' -s 'd={dumbint(i):i for i in range(1000)}' 'dumbint(-1) in d'
10000 loops, best of 3: 31.7 usec per loop
$ python -m timeit -s 'class dumbint(int):__hash__ = lambda x:0' -s 'd={dumbint(i):i for i in range(10000)}' 'dumbint(-1) in d'
1000 loops, best of 3: 803 usec per loop
字符串有一个很好的散列函数,所以你会得到 O(1) 的精确匹配查找。在键中搜索 子字符串 是一个困难得多的问题。