Python可移植哈希

2024-06-02 05:00:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读pysparkhere的源代码。我被这里的便携功能弄糊涂了。在

def portable_hash(x):
    """
    This function returns consistant hash code for builtin types, especially
    for None and tuple with None.
    The algrithm is similar to that one used by CPython 2.7
    >>> portable_hash(None)
    0
    >>> portable_hash((None, 1)) & 0xffffffff
    219750521
    """
    if x is None:
        return 0
    if isinstance(x, tuple):
        h = 0x345678
        for i in x:
            h ^= portable_hash(i)
            h *= 1000003
            h &= sys.maxint
        h ^= len(x)
        if h == -1:
            h = -2
        return h
    return hash(x)

我可以看出它是一个递归函数。如果输入是元组,则递归地遍历每个元素。在

以下是我的几个问题:

  1. 这种哈希方法是一对一的映射吗?在
  2. 此函数只接受None和tuple和 考虑到散列值,我知道列表对象不是 散列,他们有没有故意这么做。在
  3. 我对哈希没有太多的经验,这是一个非常经典的哈希方法吗?如果是,有什么资源可以让我更好地理解它吗?在

Tags: 方法功能noneforreturnif源代码is
1条回答
网友
1楼 · 发布于 2024-06-02 05:00:06

"is this hash approach an one to one mapping?"

NO哈希方法是1对1:它们都将M个可能的输入映射成N个可能的整数结果,其中M远大于N

"this function only takes None and tuple and hashable values into consideration, I know that list object is not hashable, did they do that intentionally or not."

是的,此函数委托给内置的hash除元组和None之外的所有其他内容。在Python中,让诸如listdict这样的可变内建成为不哈希的,这绝对是一个深思熟虑的设计决定(也受到这个函数的尊重)。在

"I don't have much experience with hash, is this a very classic hashing approach, if so, is there any resource for me to get a better understanding for it?"

是的,项目的exclusive-or'inghash,在执行过程中对运行的total进行修改,这确实是散列项容器的一种非常经典的方法。在

关于散列的更多研究,我将从http://en.wikipedia.org/wiki/Hash_function开始。在

相关问题 更多 >