Skip to content Skip to sidebar Skip to footer

Generating Permutations Of A Given Length - Python

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,BB

Solution 1:

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
>>> defnprod(x, n):
...     args = 'x' + (n-1)*', x'... return [''.join(z) for z ineval('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']

Post a Comment for "Generating Permutations Of A Given Length - Python"