Welcome, guest | Sign In | My Account | Store | Cart

Given a string of chars and a length, returns permutations of the specified length using the char string given in order. For example, given a string of "01" and a length of 3 returns 000, 001, 010, 011 ... 111

Python, 20 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
"""
Author: Lloyd Moore <lloyd@workharderplayharder.com>
Usage: 
	print perm("01", 2)
	> ["00", "01", "10", "11"]

	print perm("abcd", 2)
	> [ 'aa', 'ab', 'ac', 'ad', 
		'ba', 'bb', 'bc', 'bd', 
		'ca', 'cb', 'cc', 'cd', 
		'da', 'db', 'dc', 'dd' ]


"""
def perm(chars, m, wrd="", wrds=[]):
    if len(wrd) == m: return wrd
    for i in range(0, len(chars)):
        w = perm(chars, m, wrd+chars[i])
        if type(w) == type(""): wrds.append(w)
    return wrds

An alternative would be to use a generator solution for piping long computations.

3 comments

Kent Johnson 14 years, 2 months ago  # | flag

Or just use itertools:

In [11]: from itertools import product
In [12]: [ ''.join(x) for x in product('01', repeat=2) ]
Out[12]: ['00', '01', '10', '11']
manchesterboy (author) 14 years, 2 months ago  # | flag

I was aware of itertools but honestly was not aware of 'product'. Also, I was going to add an extension to use generators, but using your example using () instead of [] for the list comprehension will do the trick. Thanks for the tip.

paul stadfeld 14 years, 2 months ago  # | flag

Itertools now (3.1) does all the subsets of the Cartesian Product:

product() permutations w/replacement

permutations() permutations wo/replacement

combinations() combinations wo/replacement

combinations_with_replacement() combinations w/replacement

Created by manchesterboy on Sun, 7 Feb 2010 (MIT)
Python recipes (4591)
manchesterboy's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks