On 10-03-18 02: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

I came up with the following generalisation:

from itertools import count

def summation2(total):
    for n in range(1, total):
        yield n, total - n

def summation(total, n):
    if n == 2:
        yield from summation2(total)
        for i in range(1, total - n + 2):
            for tail in summation(total - i, n - 1):
                yield (i,) + tail

def cantor(n):
    for total in count(n):
        yield from summation(total, n)


Reply via email to