I'm trying to write an iterator for something like this (simplified from original problem):
import numpy as np
class IterableNumber:
def __init__(self, digits):
self.digits = digits
self.zero_indices = np.where(digits == 0)[0]
def __iter__(self):
return self
def next(self):
# For each index in self.zero_indices, loop 1 through 9?
pass
# Other methods omitted
The IterableNumber takes an array of numbers, but '0' is a wild card. When I loop through this object, I want each '0' digit to loop through a range of 1 through 9, i.e.
num = IterableNumber(np.array([5, 5, 0, 5, 0]))
for digits in num:
print digits
should print
[5, 5, 1, 5, 1]
[5, 5, 1, 5, 2]
...
[5, 5, 1, 5, 9]
[5, 5, 2, 5, 1]
[5, 5, 2, 5, 2]
...
...
[5, 5, 9, 5, 9]
Writing this iterator for the general case seems to require recursion in order to take care of the variable number of nested loops (one for each 0 present), as other threads on this site would suggest. But how do I write such a recursive function in the context of the iterator's next() function? Or maybe there's another way to solve this problem altogether? Any insight would be appreciated :)
I'm on python 2.7.3 if it's relevant.