Generate all combinations given a python list

Asked

Viewed 12,952 times

5

I’ve searched far enough and found nowhere exactly what I want. What I want is, given a list of characters, generate all possible combinations from size x to size y. Example: 0.1.2 and order size combinations 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 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)

1 answer

7


To generate all combinations of 8 chars from a list of 70 elements will be extremely costly, 708 (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)]

You don’t even need the for cycle (unless you need to do some more loop operation) just transform the Generator returned in a/set/tuple list 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 tuples and keep a list of strings, for this, since we have integers and no strings we have to transform them into strings:

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 just:

permsList = [''.join(x) for x in product(caracteres, repeat=2)]
  • thank you Miguel

  • You’re welcome @Júliocésar, I’m glad you decided

Browser other questions tagged

You are not signed in. Login or sign up in order to post.