Enumerating all 3-tuples
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Mar 13 07:14:29 EDT 2018
On Mon, 12 Mar 2018 13:17:15 +0000, Robin Becker wrote:
> It's possible to generalize the cantor pairing function to triples, but
> that may not give you what you want. Effectively you can generate an
> arbitrary number of triples using an iterative method. My sample code
> looked like this
>
>
> import math
>
> def cantor_pair(k1,k2):
> return (((k1+k2)*(k1+k2+1))>>1) + k2
>
> def inverse_cantor_pair(z):
> w = int((math.sqrt(8*z+1)-1)/2.0)
> t = (w*(w+1))>>1
> j = z - t
> i = w - j
> return i, j
I definitely want to avoid any round trips through float in order to use
sqrt.
But thanks for the code, I'll certainly steal it, er I mean study it for
future reference :-)
--
Steve
More information about the Python-list
mailing list