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 .

ie The ['a', 'b', 'c', 'd'], as well ['a', 'a', 'a', 'a'], and ['a', 'a', 'b', 'b']etc.

So far I have used import itertools: p = list(itertools.permutations(L, 4)). (Python 2.7.6)

However, this gives me 360 ​​unique combinations, not the 1296 that I want.

Thank!!

+4
source share
2 answers

This is a Cartesian product of 4 copies of the list. Do you want itertools.product:

import itertools
itertools.product(L, repeat=4)
+9
source

You can solve this in at least three ways.

, :

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

:

1296
Nested Iterations took 0.001148 seconds
1296
List Comprehension took 0.000299 seconds
1296
itertools.product took 0.000227 seconds

, , , itertools.product() .

N.B.: https://codepad.remoteinterview.io/. .

+1

Source: https://habr.com/ru/post/1535461/


All Articles