Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why hash function on two different objects return same value?

Tags:

python

hash

I used Spyder, run Python 2.7.

Just found interesting things:

  1. hash(-1) and hash(-2) both return -2, is there a problem? I though hash function on different object should return different values. I read previous posts that -1 is reserved as an error in Python.
  2. hash('s') returns 1835142386, then hash(1835142386) returns the same value. Is this another problem?

Thanks.

like image 934
Chenxi Zeng Avatar asked Jul 14 '16 00:07

Chenxi Zeng


1 Answers

-1 is not "reserved as an error" in Python. Not sure what that would even mean. There are a huge number of programs you couldn't write simply and clearly if you weren't allowed to use -1.

"Is there a problem?" No. Hash functions do not need to return a different hash for every object. In fact, this is not possible, since there are many more possible objects than there are hashes. CPython's hash() has the nice property of returning its argument for non-negative numbers up to sys.maxint, which is why in your second question hash(hash('s')) == hash('s'), but that is an implementation detail.

The fact that -1 and -2 have the same hash simply means that using those values as, for example, dictionary keys will result in a hash conflict. Hash conflicts are an expected situation and are automatically resolved by Python, and the second key added would simply go in the next available slot in the dictionary. Accessing the key that was inserted second would then be slightly slower than accessing the other one, but in most cases, not enough slower that you'd notice.

It is possible to construct a huge number of unequal objects all with the same hash value, which would, when stored in a dictionary or a set, cause the performance of the container to deteriorate substantially because every object added would cause a hash collision, but it isn't something you will run into unless you go looking for it.

like image 111
kindall Avatar answered Oct 03 '22 13:10

kindall