Reputation: 3
I am trying to make a generator that gives me the permutations of 3 numbers
def generador():
for i in range(3):
for j in range(3):
for k in range(3):
yield i,j,k
with a for loop for a,b,c in generador():
it work's just fine but:
for _ in range(27):
print(next(generador()))
just prints (0,0,0)
over an over again. Why?
Upvotes: 0
Views: 52
Reputation: 27485
Like has been said you’re creating the generator each iteration. You need iterate over it each iteration:
gen = generador()
for _ in range(27):
print(next(gen))
Although itertools.product
will do exactly this for you:
def generador():
yield from itertools.product(range(3), repeat=3)
Upvotes: 2
Reputation: 739
You need to latch the generator to a variable and next
through that so youre going through the same instance, otherwise you're going through a new instance each loop, hence you're getting 0,0,0
def generador():
for i in range(3):
for j in range(3):
for k in range(3):
yield i,j,k
a = generador()
for _ in range(27):
print(next(a))
Upvotes: 1