Reputation: 198
I want to iterate over n arrays in a certain way. The number of arrays is undefined.
This would be an example:
this entry:
[['A', 'B', 'C'], ['D', 'E'], ['F', 'G']]
This output should be printed:
[ADF, ADG, AEF, AEG, BDF, BDG, BEF, BEG, CDF, CDG, CEF, CEG]
To be more specific with the way to order them:
ADF - ADG - AEF - AEG - BDF - BDG - BEF - BEG - CDF - CDG - CEF - CEG
111 112 121 122 211 212 221 222 311 312 321 322
Where the numbers are the index of each letter in the previous arrays.
another example:
Input:
[['A', 'B', 'C'], ['D', 'E'], ['F', 'G', 'H']]
Output:
ADF - ADG - ADH - AEF - AEG - AEH - BDF - BDG - BDH - BEF - BEG - BEH - CDF - CDG - CDH - CEF - CEG - CEH
111 112 113 121 122 123 211 212 213 221 222 223 311 312 313 321 322 323
Is there a way to make a recursive function to obtain that order? I tried to find a pattern with the length of each array, but I could not find this solution. I'm trying to do it in python
Upvotes: 0
Views: 45
Reputation: 18668
it is just a product :
from itertools import product
[''.join(x) for x in product(['A', 'B', 'C'], ['D', 'E'], ['F', 'G'])]
# ['ADF', 'ADG', 'AEF', 'AEG', 'BDF', 'BDG', 'BEF', 'BEG', 'CDF', 'CDG', 'CEF', 'CEG']
The recursive way:
def prod (sets):
if not sets : return ['']
res=[]
for x in sets[0]:
for y in prod(sets[1:]):
res.append (x+y)
return res
Upvotes: 2