Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple permutations, including duplicates

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!!

like image 637
user3509103 Avatar asked Dec 15 '22 23:12

user3509103


2 Answers

This is a cartesian product of 4 copies of the list. You want itertools.product:

import itertools
itertools.product(L, repeat=4)
like image 77
user2357112 supports Monica Avatar answered Dec 28 '22 08:12

user2357112 supports Monica


One can solve this in at least 3 ways.

  1. Using nested loop
  2. Using list comprehensions
  3. Using itertools.product()

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.

like image 25
arsho Avatar answered Dec 28 '22 08:12

arsho