比较 hash es 用于一些二元组
for i in range(11):
print(i, hash((i,i)) == hash((-i,-i)))
我希望在 i==0
时得到 True
,在其余情况下得到 False
。我很惊讶地看到这个:
0 True
1 False
2 True
3 True
4 True
5 True
6 True
7 True
8 False
9 True
10 True
为什么会这样?
据我所知,这与 this 中的问题不同问题,因为这与顺序无关,而与值(value)观本身有关。
最佳答案
散列值永远无法保证无冲突,即使优秀的散列算法努力做到这一点。 Python 3.8 改进了哈希算法,特别是针对元组的哈希算法,因此与 Python 3.7 相比,问题中的问题现在变得更难在 Python 3.8 中重现。
摘自 changelog for Python 3.8.0 alpha 1 :
bpo-34751: The hash function for tuples is now based on xxHash which gives better collision results on (formerly) pathological cases. Additionally, on 64-bit systems it improves tuple hashes in general. Patch by Jeroen Demeyer with substantial contributions by Tim Peters.
关于python - 元组上的哈希输出不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61275518/