Python快速包含方法

时间:2013-11-14 00:05:28

标签: python dictionary key contains

如果我在Python中有字典,那么搜索不存在的密钥的时间复杂度是多少?

d = {}
if key not in d:
   print "Key not found!"

in是否对密钥数组进行线性搜索?

是否有针对特定字符串搜索数据结构的O(1)实现?有效地使用contains()方法。

3 个答案:

答案 0 :(得分:2)

对于字典,它必须分摊O(1),因为最后in运算符只是执行成员资格查找,not没有额外的开销。有关字典情况下in运算符的时间复杂度的更多详细信息,请查看此answer

答案 1 :(得分:1)

它的O(1)字典被实现为哈希表并且在哈希表查找中实现

答案 2 :(得分:1)

字典通常 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)查找。在密钥中搜索子字符串是一个更加困难的问题。