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)
?
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
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)
?
Use itertools.product()
instead:
from itertools import product
def foo(point):
for combo in product(*(range(i + 1) for i in point)):
yield combo