0

I want to generate a list of permutations over a given alphabet of length n. For example, if n = 3 and the alphabet includes {A,B}, output should be: AAA,AAB,ABA,BAA,ABB,BAB,BBA,BBB

Tonechas
  • 13,398
  • 16
  • 46
  • 80
Minon Weerasinghe
  • 312
  • 1
  • 3
  • 13

1 Answers1

0

I'm guessing from the desired output that you want to generate the cartesian product of an alphabet with itself repeated n times rather than a list of permutations. This admittedly tricky wrapper of itertools.product() will do the job just fine:

>>> import itertools
>>> def nprod(x, n):
...     args = 'x' + (n-1)*', x'
...     return [''.join(z) for z in eval('itertools.product(%s)' % args)]
...
>>> nprod('AB', 3)
['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB']
>>> nprod(['1', '2', '3'], 2)
['11', '12', '13', '21', '22', '23', '31', '32', '33']

EDIT: Oh, silly me!!! I didn't notice in the documentation the optional repeat keyword argument :D

>>> [''.join(x) for x in itertools.product('AB', repeat=3)]
['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB']
>>>> [''.join(x) for x in itertools.product(['1', '2', '3'], repeat=2)]
['11', '12', '13', '21', '22', '23', '31', '32', '33']
Tonechas
  • 13,398
  • 16
  • 46
  • 80
  • 1
    If you weren't able to use `repeat`, surely `itertools.product(*[x]*n)` would be nicer than using `eval`? – Blckknght May 13 '16 at 21:13