为什么python3为-1和-2生成相同的哈希值?

时间:2018-02-09 00:48:49

标签: python hash python-3.5 hash-collision

我正在为任意值尝试python3内置hash()方法,然后是范围,我看到了一些有趣的东西:

>>> [hash(i) for i in range(-20,20)]
[-20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

为整数生成的哈希值通常是整数本身,除了-1,由于某种原因,-1也是-2,也是-2的哈希值。

我的Python3解释器是:

Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux

这也可以在其他地方复制,例如repl.it,它产生:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
hash(1)
=> 1
[hash(i) for i in range(-20,20)]
=> [-20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]   

<iframe height="400px" width="100%" src="https://repl.it/@aalok_sathe/FairCornflowerblueLadybug?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe>

据我所知,哈希可能会产生碰撞,如果碰到这种情况,我就不会发现它会在这么小的范围内发生。 我正在寻找可以帮助解释这种行为的任何东西,以及当我真正需要在程序中使用它时可以使用的任何替代/变通方法的任何提示(我能想到的是将整数转换为字符串然后进行散列,但这不允许具有不同散列值的不同类型)。除了应用程序细节之外,我对此感到困惑,所以任何指针都会有所帮助。

0 个答案:

没有答案