I work with multidimensional structures of arbitrary dimension. I have a Python list of xrange iterators, with each iterator representing an index of a multidimensional array:
indices = [ i, j, k ]
where
i = xrange(1,3)
j = xrange(3,5)
k = xrange(5,7)
To generate all the possible values, I use the following naive recursive code:
def travtree(index,depth):
"Recursion through index list"
if depth >= len(indices):
# Stopping Condition
print index
else:
# Recursion
currindexrange = indices[depth]
for currindex in xrange(len(currindexrange)):
newindex = list(index) # list copy
newindex.append(currindexrange[currindex])
travtree(newindex,depth+1)
travtree([],0)
This works fine, but I was wondering, is there a more efficient, Pythonic way to do this? I tried looking in the itertools module but nothing jumps out at me.
1 Answer