On 10/03/2018 01:13, Steven D'Aprano wrote:
I am trying to enumerate all the three-tuples (x, y, z) where each of x,
y, z can range from 1 to ∞ (infinity).
This is clearly unhelpful:
for x in itertools.count(1):
for y in itertools.count(1):
for z in itertools.count(1):
print(x, y, z)
as it never advances beyond x=1, y=1 since the innermost loop never
finishes.
Georg Cantor to the rescue! (Well, almost...)
https://en.wikipedia.org/wiki/Pairing_function
The Russian mathematician Cantor came up with a *pairing function* that
encodes a pair of integers into a single one. For example, he maps the
coordinate pairs to integers as follows:
1,1 -> 1
2,1 -> 2
1,2 -> 3
3,1 -> 4
2,2 -> 5
and so forth. He does this by writing out the coordinates in a grid:
1,1 1,2 1,3 1,4 ...
2,1 2,2 2,3 2,4 ...
3,1 3,2 3,3 3,4 ...
4,1 4,2 4,3 4,4 ...
...
...
But I've stared at this for an hour and I can't see how to extend the
result to three coordinates. I can lay out a grid in the order I want:
1,1,1 1,1,2 1,1,3 1,1,4 ...
2,1,1 2,1,2 2,1,3 2,1,4 ...
1,2,1 1,2,2 1,2,3 1,2,4 ...
3,1,1 3,1,2 3,1,3 3,1,4 ...
2,2,1 2,2,2 2,2,3 2,2,4 ...
...
I can't see the patterns here that I can see in the 2-D grid (where the
first number in each pair in the n'th row is n, and the second number in
the n'th column is n).
Maybe it needs to be 3-D? (Eg if the 3rd number in the triple is the
Plane number, then plane 1 looks like:
1,1,1 1,2,1 1,3,1
2,1,1 2,2,1 2,3,1
3,1,1 3,2,1 3,3,1 ...
...
But whether that has an equivalent traversal path like the diagonals of
the 2-D, I don't know. I'm just guessing.)
--
bartc
--
https://mail.python.org/mailman/listinfo/python-list