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
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.
Or just use itertools:
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.
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