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
Asked
Active
Viewed 498 times
0

Tonechas
- 13,398
- 16
- 46
- 80

Minon Weerasinghe
- 312
- 1
- 3
- 13
-
Have you tried typing the title of your question in the search box? – m69's been on strike for years May 07 '16 at 17:01
-
http://stackoverflow.com/questions/10342939/power-set-and-cartesian-product-of-a-set-python treats the same topic. – fgoettel May 13 '16 at 18:51
-
@deloz: Indeed the accepted answer to the question you mention solves the problem for ``n=2``, but the OP is interested in a general solution for any value of ``n`` – Tonechas May 13 '16 at 19:06
1 Answers
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
-
1If 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