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 def cantor_triple(i,j,k): return cantor_pair(cantor_pair(i,j),k) def inverse_cantor_triple(z): j,k = inverse_cantor_pair(z) i,j = inverse_cantor_pair(j) return i,j,k if __name__=='__main__': for z in xrange(100): i,j,k = inverse_cantor_triple(z) print z, repr((i,j,k)) or changing the construction 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 def cantor_triple(i,j,k): return cantor_pair(i,cantor_pair(j,k)) def inverse_cantor_triple(z): i,k = inverse_cantor_pair(z) j,k = inverse_cantor_pair(k) return i,j,k if __name__=='__main__': for z in xrange(100): i,j,k = inverse_cantor_triple(z) print z, repr((i,j,k)), cantor_triple(i,j,k)==z this give different outcomes, but both appear to be a correct mapping of non-negative integers to triplets. -- Robin Becker -- https://mail.python.org/mailman/listinfo/python-list
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
- Re: Enumerating all 3-tuples Elliott Roper
- Re: Enumerating all 3-tuples Steven D'Aprano
- Re: Enumerating all 3-tuples Paul Moore
- Re: Enumerating all 3-tuples Ben Bacarisse
- Re: Enumerating all 3-tuples Ben Bacarisse
- Re: Enumerating all 3-tuples Ben Bacarisse
- Re: Enumerating all 3-tuples bartc
- Re: Enumerating all 3-tuples Ben Bacarisse
- Re: Enumerating all 3-tuples bartc
- Re: Enumerating all 3-tuples Ben Bacarisse
- Re: Enumerating all 3-tuples Robin Becker
- Re: Enumerating all 3-tuples Robin Becker
- Re: Enumerating all 3-tuples Chris Angelico
- Re: Enumerating all 3-tuples Skip Montanaro
- Re: Enumerating all 3-tuples Chris Angelico
- Re: Enumerating all 3-tuples Robin Becker
- Re: Enumerating all 3-tuples Steven D'Aprano
- Re: Enumerating all 3-tuples Robin Becker
- Re: Enumerating all 3-tuples (Posting On Python-L... Ben Bacarisse
- Re: Enumerating all 3-tuples (Posting On Pyth... Ben Bacarisse
- Re: Enumerating all 3-tuples (Posting On ... Ben Bacarisse