2

I have a dictionary with items and the number of reps for each item, for example:

{A: 3, B: 1}

I'm looking for a way to get all possible different combinations, The order doesn't matter: [AB] is the same as [BA].

The wanted output is:

[A, AA, AAA, B, AB, AAB, AAAB]
yatu
  • 86,083
  • 12
  • 84
  • 139
Gal Perelman
  • 47
  • 1
  • 4

1 Answers1

0

Here's a way using list comprehensions and itertools.product:

from itertools import product, chain
d = {'A': 3, 'B': 1}
l = [[k*i for i in range(1,v+1)] for k, v in d.items()]
[''.join(element) for element in product(*l)] + list(chain.from_iterable(l))

Output:

['AB', 'AAB', 'AAAB', 'A', 'AA', 'AAA', 'B']

Details:

The result of the first list comprehension is a nested list where each sublist has each of the keys contained in the dictionary repeated from 1 up to its corresponding value:

[['A', 'AA', 'AAA'], ['B']]

The second one, performs the cartesian product using itertools.product, and each product is joined into a string. Finally a flattened version of l is added using chain.from_iterable:

print(list(chain.from_iterable(l)))
['A', 'AA', 'AAA', 'B']

[''.join(element) for element in product(*l)]
['AB', 'AAB', 'AAAB']
yatu
  • 86,083
  • 12
  • 84
  • 139