gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:39:43 29 4
gpt4 key购买 nike

功能如何 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com