Generate all combinations given a list in python

5

I have searched extensively and found nowhere exactly what I want. What I want is, given a list of characters, to generate all possible combinations of size x up to size y. Example: given 0,1,2 and ask combinations of size from 1 to 2 generate: (00) (11) (22) (01) (10) (02) (20) (12) (21)

I wanted to generate, for example, all combinations of 8 to 20 characters given a list of 70 characters (I know it would be extremely large).

The code I've made:

from itertools import permutations

caracteres = [0, 1, 2]
for subset in permutations(caracteres, 2):
    print(subset)

generates only: (01) (02) (10) (12) (20) (21)

    
asked by anonymous 15.08.2016 / 07:24

1 answer

7

To generate all 8-chars combinations from a list of 70 elements will be extremely costly, 70 8 (576,480,100,000,000) combinations ... Good luck: P

To generate all possible combinations, including repeated characters, use product :

from itertools import product

caracteres = [0, 1, 2]
permsList = []
genComb = product(caracteres, repeat=2) # aqui e onde tens de especificar o numero de chars que cada combinacao tenha
for subset in genComb:
    print(subset) # tuple retornado com uma combinacao por loop
    permsList.append(subset)
print(permsList) # [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Neither do you need the for loop (unless you need to do some more operation in the loop) simply turn generator returned in a list / set / tuple to store the results, all you need is this:

from itertools import product

caracteres = [0, 1, 2]
permsList = list(product(caracteres, repeat=2))
print(permsList) # [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

You can also remove the tuples and get a list of strings, for this, since we have integers and not strings we have to transform them into string:

from itertools import product

caracteres = [0, 1, 2]
permsList = [''.join(str(i) for i in x) for x in product(caracteres, repeat=2)]
print(permsList) # ['00', '01', '02', '10', '11', '12', '20', '21', '22']

If you have strings instead of integers in tuples, you can only:

permsList = [''.join(x) for x in product(caracteres, repeat=2)]
    
15.08.2016 / 11:51