I have an unknown number of Integer variables say that can range from [0,9] I want to iterate over all permutations of these values.
If the number of variables was constant, it would be easy to write nested for loops. I came up with a recursive function that does what I want, but was curious if there was a way to do it iteratively.
def nested(array,index):
n = len(array)
for i in range(10):
array[n-index]=i
#len(array-1) end of array
if(index == 1):
print(array)
#do something later
else:
nested(array,index-1)
#generate all permutations, change n to change size of list.
n = 4
array = [0]*n
nested(array,len(array))
I tried using the so called "Simple Method" found here -> http://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html But I couldn't get it to work.
As was mentioned by another commenter, the key is to simulate your tail recursion using a stack.
Take note I append()
a tuple of (array, index)
into the stack
, which mirrors the call to recursive function in your original recursive solution. At the start of the iteration, it does stack.pop()
, which mimics the body of your recursive function. Recursive call becomes stack.append()
.
def nested(array):
stack = []
n = len(array)
stack.append((array.copy(), n))
while(stack):
array, index = stack.pop()
for i in range(10):
array[n-index]=i
#len(array-1) end of array
if(index == 1):
print(array)
#do something later
else:
stack.append((array.copy(), index-1))
#generate all permutations, change n to change size of list.
n = 4
array = [0]*n
nested(array)
Please refer to itertools . There is a Class "permutations" that could solve your problem perfectly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.