How to make function foo generate all the points?

Question:

Here is my code:

point = (3,6,9) # let all the elements of the tuple be none negative integers


def foo(point):
    for i in range(point[0]+1):
        for j in range(point[1]+1):
            for k in range(point[2]+1):
                yield (i,j,k)

My question is:
What if I don’t know the length of the tuple in advance?
How to make function foo take any tuple as argument and do the same thing? e.g. what if point = (3,6,9,0,7) ?

Asked By: du369

||

Answers:

Use itertools.product() instead:

from itertools import product

def foo(point):
    for combo in product(*(range(i + 1) for i in point)):
        yield combo
Answered By: Martijn Pieters
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.