I am trying to convert a for loop into an iterator using yield, but I have failed in my attempts. I don't understand exactly why the yield isn't giving me the expected output. Does anyone know what the problem is?
Attempt at using yield:
def iteration_order(dimensions):
for dim in range(dimensions):
order = [0, dim, 0]
yield order
for j in range(6):
sgn = 1 if j % 2 == 0 else -1
idx = j % 3
for _ in range(dim if j < 5 else dim-1):
order[idx] += sgn
yield order
print(list(iteration_order(2))
>>> [[0, 0, 0], [0, 1, 1], [0, 1, 1], [0, 1, 1], [0, 1, 1], [0, 1, 1], [0, 1, 1]]
The code as it should work (when not using yield):
def iteration_order(dimensions):
full_order = []
for dim in range(dimensions):
order = [[0, dim, 0]]
for j in range(6):
sgn = 1 if j % 2 == 0 else -1
idx = j % 3
for _ in range(dim if j < 5 else dim-1):
nxt = list(order[-1])
nxt[idx] += sgn
order.append(nxt)
full_order.extend(order)
return full_order
print(iteration_order(2))
>>> [[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1], [0, 1, 1]]
hex_array=np.zeros((dims*2,dims*2)), i can writei=0; for order in iteration_order(dims): hex_array[dims+ordr[0]-ordr[2], dims+ordr[1]-ordr[0]] = i; i += 1