2

I have a class whose instances have two atributes each with an integer. I want to create a __hash__ method for it and my first choice was using the Cantor pairing function:

cantor(x, y) = 0.5 * (x + y) * (x + y + 1) + y

that returns an unique integer given two unique integers. But the only problem with this is it starts returning really large numbers very fast and I was wondering if there's a better way to do it.

  • 8
    why not just `hash((x, y))`? – Samwise Feb 01 '22 at 20:40
  • 3
    Does this answer your question? [What's a correct and good way to implement \_\_hash\_\_()?](https://stackoverflow.com/questions/2909106/whats-a-correct-and-good-way-to-implement-hash) – buran Feb 01 '22 at 20:41
  • first: just returning the tuple hash as @Samwise commented should be good. Second: what is the problem with "really large" numbers? Unless you are talking numbers with 10s of digits for x and y, that should not matter. Python integers are not limited to 2**64, you know. (Maybe you'd prefer dropping that "0.5" which will convert your hash to a float, instead of an int. – jsbueno Feb 03 '22 at 14:31

0 Answers0