Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different python frozensets with same hash value

My understanding is that hashing two different frozensets (immutable Python sets), which need to contain hashable objects, should lead to two different hashes. Why do I get the output below for two different frozensets?

In [11]: a
Out[11]: frozenset({(2, -2), (2, -1), (3, -2), (3, -1)})

In [12]: b
Out[12]: frozenset({(4, -2), (4, -1), (5, -2), (5, -1)})

In [13]: hash(a)
Out[13]: 665780563440688

In [14]: hash(b)
Out[14]: 665780563440688
like image 216
Roy Avatar asked Apr 30 '15 03:04

Roy


People also ask

Is Python hash consistent?

As noted by many, Python's hash is not consistent anymore (as of version 3.3), as a random PYTHONHASHSEED is now used by default (to address security concerns, as explained in this excellent answer).

Are Frozen sets hashable?

Frozen set being immutable are hashable, can be used as a “key” for dictionaries or elements for another set object. Frozen set is constructed using “frozenset()” function.

What is the difference between id and hash in Python?

Unequal objects may have the same hash values. Equal objects need to have the same id values. Whenever obj1 is obj2 is called, the id values of both objects is compared, not their hash values.

Can lists be hashed Python?

Python immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id .


1 Answers

You seem to have stumbled upon two frozensets with equal hash codes and different contents. This is not so strange as it may seem as the property of hash codes are that they are guaranteed to be equal for equal objects and probably different for non-equal objects.

From the Python docs:

hash(object) -> integer

Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely.

The absolute easiest example of this are the numbers -1 and -2 which have the same hash code in python:

>>> print(hash(-1))
-2
>>> print(hash(-2))
-2
like image 145
Raniz Avatar answered Sep 29 '22 05:09

Raniz