I've tried searching for an answer to this question and read a lot about decorators and global variables, but have not found anything that exactly makes sense with the problem at hand: I want to make every permutation of N
-length using A
-alphabet, fxn(A,N)
. I will pass the function 2 arguments: A
and N
. It will make dummy result of length N
. Then, with N
nested for
loops it will update each index of the result with every element of A
starting from the innermost loop. So with fxn(‘01’,4)
it will produce
1111, 1110, 1101, 1100, 1011, 1010, 1001, 1000,
0111, 0110, 0101, 0100, 0011, 0010, 0001, 0000
It is straightforward to do this if you know how many nested loops you will need (N
; although for more than 4 it starts to get really messy and cumbersome). However, if you want to make all arbitrary-length sequences using A, then you need some way to automate this looping behavior. In particular I will also want this function to act as a generator to prevent having to store all these values in memory, such as with a list. To start it needs to initialize the first loop and keep initializing nested loops with a single value change (the index to update) N-1
times. It will then yield the value of the innermost loop.
The straightforward way to do fxn('01',4)
would be:
for i in alphabet:
tempresult[0] = i
for i in alphabet:
tempresult[1] = i
for i in alphabet:
tempresult[2] = i
for i in alphabet:
tempresult[3] = i
yield tempresult
Basically, how can I extend this to an arbitrary length list or string and still get each nest loop to update the appropriate index. I know there is probably a permutation function as part of numpy that will do this, but I haven't been able to come across one. Any advice would be appreciated.