geogeek
geogeek

Reputation: 1302

Get Unique value "Hashcode" from a Set

i wanna represent a set of two int values as one value, so i can have:

x = f(a,b) = f(b,a)

so x should not represent more than one set.

Any help please.

Upvotes: 0

Views: 455

Answers (2)

Blckknght
Blckknght

Reputation: 104792

The frozenset type is hashable, and you can create one from any iterable. To get the hash value, just use the built-in hash function:

x = hash(frozenset([a, b]))

Upvotes: 1

Emmanuel
Emmanuel

Reputation: 14209

If you don't want an integer as value for x, I think returning the ordered tuple should be ok (it works for all number of values):

>>> s = {1, 2}
>>> s2 = {2, 1}
>>> f = lambda s: tuple(sorted(s))
>>> f(s)
(1, 2)
>>> f(s2)
(1, 2)
>>> f(s) == f(s2)
True

Upvotes: 0

Related Questions