从哈希集添加和检索字符串的时间复杂度是什么

时间:2019-11-05 17:02:25

标签: python hash hashset

假设我们将一组长字符串添加到哈希集中,然后测试此哈希集中是否已经存在一些字符串。添加和检索操作的时间复杂度是否恒定?还是取决于字符串的长度?

例如,如果我们有三个字符串。

s1 = 'abcdefghijklmn'
s2 = 'dalkfdboijaskjd'
s3 = 'abcdefghijklmn'

然后我们这样做:

pool = set()
pool.add(s1)
pool.add(s2)
print s3 in pool # => True
print 'zzzzzzzzzz' in pool # => False

上述操作的时间复杂度是否会成为字符串长度的因素?

另一个问题是,如果我们对一个元组进行散列怎么办?像(1,2,3,4,5,6,7,8,9)之类的东西?

感谢您的帮助!

=================================

我了解到this one之类的资源正在讨论为什么哈希是恒定时间和冲突问题。但是,他们通常认为密钥的长度可以忽略。这个问题问,当密钥的长度不可忽略时,哈希是否仍具有恒定的时间。例如,如果要判断N次是否是长度为K的密钥,则时间复杂度为O(N)或O(N * K)。

4 个答案:

答案 0 :(得分:0)

Wiki是你的朋友

https://wiki.python.org/moin/TimeComplexity

对于上述操作,对于set,它们似乎都是O(1)

答案 1 :(得分:0)

严格来说,它取决于哈希集的实现以及您使用它的方式(在特殊情况下,可能有一些聪明的方法可以优化某些时间),但是总的来说,您应该期望将密钥散列进行插入或查找将花费O(n)时间,其中n是密钥的大小。通常将哈希集假定为O(1),但是有一个隐式假设,即密钥的大小是固定的,对它们进行哈希处理是O(1)操作(换句话说,假设密钥大小可以忽略)与集合中的项目数进行比较。

优化真正的大块数据的存储和检索是数据库成为一回事的原因。 :)

答案 2 :(得分:0)

平均情况为O(1)。 但是,最坏的情况是O(n),其中n是集合中元素的数量。这种情况是由哈希冲突引起的。 你可以在这里了解更多 https://www.geeksforgeeks.org/internal-working-of-set-in-python/

答案 3 :(得分:0)

回答类似问题的最好方法之一就是深入研究实现方法:)

尽管setobject.c标头中描述了一些optimization magic,但adding an object into a set重用了曾经调用过hash()的字符串中的哈希值(回想起,字符串是不可变的)或calls the type's hash implementation

对于Unicode /字节对象,我们最终通过here_Py_HashBytes,这似乎对小字符串进行了优化,否则它使用了编译时配置的哈希函数,所有这些自然有点O(n)-ish。但同样,每个字符串对象似乎只发生一次。

对于元组,可以在here中找到哈希实现-显然是简化的,非缓存的xxHash。

但是,一旦计算出哈希值,the time complexity for sets should be around O(1)

编辑:一个快速但不太科学的基准:

import time


def make_string(c, n):
    return c * n


def make_tuple(el, n):
    return (el,) * n


def hashtest(gen, n):
    # First compute how long generation alone takes
    gen_time = time.perf_counter()
    for x in range(n):
        gen()
    gen_time = time.perf_counter() - gen_time

    # Then compute how long hashing and generation takes
    hash_and_gen_time = time.perf_counter()
    for x in range(n):
        hash(gen())
    hash_and_gen_time = time.perf_counter() - hash_and_gen_time

    # Return the two
    return (hash_and_gen_time, gen_time)


for gen in (make_string, make_tuple):
    for obj_length in (10000, 20000, 40000):
        t = f"{gen.__name__} x {obj_length}"
        # Using `b'hello'.decode()` here to avoid any cached hash shenanigans
        hash_and_gen_time, gen_time = hashtest(
            lambda: gen(b"hello".decode(), obj_length), 10000
        )
        hash_time = hash_and_gen_time - gen_time
        print(t, hash_time, obj_length / hash_time)

输出

make_string x 10000 0.23490356100000004 42570.66158311665
make_string x 20000 0.47143921999999994 42423.284172241765
make_string x 40000 0.942087403 42458.905482254915
make_tuple x 10000 0.45578034300000025 21940.393335480014
make_tuple x 20000 0.9328520900000008 21439.62608263008
make_tuple x 40000 1.8562772150000004 21548.505620158674

基本上说哈希序列(是字符串还是元组)是线性时间,但是哈希字符串比哈希元组要快得多。

编辑2:这证明字符串和字节字符串缓存其哈希值:

import time
s = ('x' * 500_000_000)
t0 = time.perf_counter()
a = hash(s)
t1 = time.perf_counter()
print(t1 - t0)
t0 = time.perf_counter()
b = hash(s)
t2 = time.perf_counter()
assert a == b
print(t2 - t0)

输出

0.26157095399999997
1.201999999977943e-06
相关问题