I have a list of 6 elements L = ['a', 'b', 'c', 'd', 'e', 'f']
and would like to generate all possible 4 letter combinations - including duplicate values.
i.e ['a', 'b', 'c', 'd']
as well as ['a', 'a', 'a', 'a']
and ['a', 'a', 'b', 'b']
, etc.
So far I have been using import itertools: p = list(itertools.permutations(L, 4))
. (Python 2.7.6)
However, this is only giving me the 360 unique combinations, rather than the 1296 that I want.
Thanks!!
This is a cartesian product of 4 copies of the list. You want itertools.product
:
import itertools
itertools.product(L, repeat=4)
One can solve this in at least 3 ways.
Let's see how to use these and deep into the time performance of these:
from time import time
# Solution 1
time_start = time()
L = ['a', 'b', 'c', 'd', 'e', 'f']
ar = []
for a in L:
for b in L:
for c in L:
for d in L:
ar.append([a,b,c,d])
print(len(ar))
time_end = time()
print('Nested Iterations took %f seconds' %(time_end-time_start))
# Solution 2
time_start = time()
L = ['a', 'b', 'c', 'd', 'e', 'f']
ar = [[a,b,c,d] for a in L for b in L for c in L for d in L]
print(len(ar))
time_end = time()
print('List Comprehension took %f seconds' %(time_end-time_start))
# Solution 3
import itertools
time_start = time()
L = ['a', 'b', 'c', 'd', 'e', 'f']
ar = list(itertools.product(L, repeat = 4))
print(len(ar))
time_end = time()
print('itertools.product took %f seconds' %(time_end-time_start))
Output:
1296
Nested Iterations took 0.001148 seconds
1296
List Comprehension took 0.000299 seconds
1296
itertools.product took 0.000227 seconds
So, comparing the ways we see that itertools.product()
is simpler and effective than the others.
N.B.: The code is run in https://codepad.remoteinterview.io/. Performance may vary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With