python - hash() 如何计算元组的哈希值?

标签 python hashcode

功能如何 hash() 计算元组的哈希值?例如:

t = (1,2,3)
print(hash(t))

给出一个输出
-378539185

最佳答案

如果您熟悉 C 编程和一些高级数学,您可以检查 implementation of this function in C。似乎算法对元组中每个元素的散列进行异或运算,并增加了一些魔法。

static Py_hash_t
tuplehash(PyTupleObject *v)
{
    Py_uhash_t x;  /* Unsigned for defined overflow behavior. */
    Py_hash_t y;
    Py_ssize_t len = Py_SIZE(v);
    PyObject **p;
    Py_uhash_t mult = _PyHASH_MULTIPLIER;
    x = 0x345678UL;
    p = v->ob_item;
    while (--len >= 0) {
        y = PyObject_Hash(*p++);
        if (y == -1)
            return -1;
        x = (x ^ y) * mult;
        /* the cast might truncate len; that doesn't change hash stability */
        mult += (Py_hash_t)(82520UL + len + len);
    }
    x += 97531UL;
    if (x == (Py_uhash_t)-1)
        x = -2;
    return x;
}

请注意,这是 CPython 的当前实现。其他 Python 解释器甚至其他版本的 CPython 可能具有不同的哈希函数。这个称为 SipHash 的特定实现自 2013 年以来一直在使用。有关详细说明,请参阅 PEP 456 -- Secure and interchangeable hash algorithm

SipHash is a cryptographic pseudo random function with a 128-bit seed and 64-bit output.... SipHash is a family of pseudorandom functions (a.k.a. keyed hash functions) optimized for speed on short messages. Target applications include network traffic authentication and defense against hash-flooding DoS attacks.

关于python - hash() 如何计算元组的哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51593173/

相关文章:

python - 在 scipy.optimize.root 中计算 Jacobian 的默认选项

python - 如何从 Tk Text() 对象中删除所有标签

java - 关于Hash Set中的contains方法的问题

jquery - 从另一个页面链接到特定选项卡

java - HashSet 添加重复对象

java - 为什么 main 方法中 args 的哈希码仅限于某些值集?

java - java中如何获取一个对象的父对象引用?

python - 有没有办法更改 Pandas 数据透视表的边距 "All"列位置?

Python 正则表达式全局用空格替换尾随零

python - 按递增顺序重命名具有相同名称的多个不同扩展名的文件