0

Maybe it's not so simple, but I am trying to essentially find all the permutations of a list of letters.

[[a,b],[c,d],[e,f]] for simplicity as it can be longer than just 3 lists of 2 (ie 6 lists of 3 letters, etc.).

I want my program to find all 8 combinations for above example while maintaining order of the main list (is that permutation?).

ace
acf
ade
adf
bce
bcf
bde
bdf

Currently I think the solution below will iterate recursively through the combinations I want; however, I cannot figure out how to store them in order because when it reaches the base condition for the first row it will simply go to the next letter in the last index of the list.

I don't believe I was able to find something that would work for me in itertools

def find_comb(mylist):

    for curr_index in range(0,len(mylist)):

        for letter in mylist[curr_index]:           

            if (curr_index+1<=len(mylist)):
               next_letter=find_comb(mylist[curr_index+1:])

    return 1     #wrote 1 for now because I am stumped
nchuang
  • 83
  • 8
  • 1
    Possible duplicate of [Get the cartesian product of a series of lists in Python](http://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists-in-python) – Colonel Beauvel Apr 11 '16 at 15:06
  • For argument's sake since I struggled with this for a while, if I was to fix what I have already how would I keep track of each permutation/product? – nchuang Apr 11 '16 at 17:29
  • what do you mean by 'keep track of each permutation/product' ? – Colonel Beauvel Apr 11 '16 at 20:33

1 Answers1

1

I think what you want is itertools.product

from itertools import product

x = [['a','b'], ['c','d'], ['e','f']]

for _ in product(*x):
    print _

Prints

('a', 'c', 'e')
('a', 'c', 'f')
('a', 'd', 'e')
('a', 'd', 'f')
('b', 'c', 'e')
('b', 'c', 'f')
('b', 'd', 'e')
('b', 'd', 'f')

Regarding your comment:

product takes a bunch of iterables and generates their product, however, in your case you were sending it a single iterable (that consisted of more iterables). So instead of passing in l1, l2, l3 you were passing in[l1, l2, l3].

To actually pass in the three iterables, we have to unpack the list using the asterisk, which will turn that single list into three arguments. For more on that, see What does ** (double star) and * (star) do for parameters?

Community
  • 1
  • 1
Bahrom
  • 4,752
  • 32
  • 41
  • Oh wow. i saw that, but it kept giving me a reference error. I didn't know I had to write it like that. I just simply wrote: `x=itertools.product(mylist)` `print(x)` what does the asterisk mean and why did I have to iterate to print it correctly? – nchuang Apr 11 '16 at 15:10