When is hash(n) == n in Python?

前端 未结 4 503
广开言路
广开言路 2021-01-30 05:08

I\'ve been playing with Python\'s hash function. For small integers, it appears hash(n) == n always. However this does not extend to large numbers:

         


        
4条回答
  •  自闭症患者
    2021-01-30 05:18

    Hash function returns plain int that means that returned value is greater than -sys.maxint and lower than sys.maxint, which means if you pass sys.maxint + x to it result would be -sys.maxint + (x - 2).

    hash(sys.maxint + 1) == sys.maxint + 1 # False
    hash(sys.maxint + 1) == - sys.maxint -1 # True
    hash(sys.maxint + sys.maxint) == -sys.maxint + sys.maxint - 2 # True
    

    Meanwhile 2**200 is a n times greater than sys.maxint - my guess is that hash would go over range -sys.maxint..+sys.maxint n times until it stops on plain integer in that range, like in code snippets above..

    So generally, for any n <= sys.maxint:

    hash(sys.maxint*n) == -sys.maxint*(n%2) +  2*(n%2)*sys.maxint - n/2 - (n + 1)%2 ## True
    

    Note: this is true for python 2.

提交回复
热议问题