On May 7, 11:34 pm, [EMAIL PROTECTED] wrote: > On May 7, 10:45 pm, Michael Tobis <[EMAIL PROTECTED]> wrote: > > > > > I want a list of all ordered permutations of a given length of a set > > of tokens. Each token is a single character, and for convenience, they > > are passed as a string in ascending ASCII order. > > > For example > > > permute("abc",2) > > > should return ["aa","ab","ac","ba","bb","bc","ca","cb","cc"] > > > and permute("13579",3) should return a list of 125 elements > > ["111","113", ... ,"997","999"] > > > permute("axc",N) or permute("2446",N) should raise ValueError as the > > alphabet is not strictly sorted. > > > I have a reasonably elegant solution but it's a bit verbose (a couple > > dozen lines which I'll post later if there is interest). Is there some > > clever Pythonism I didn't spot? > > > thanks > > mt > > Post yours.
Oh well, as I'm not the first. def p(a,b): if list( a ) != sorted( list( a ) ): raise ValueError, "String not ordered." if not b: return [''] a = sorted( set( a ) ) return [i+j for i in a for j in p(a,b-1)] p('abc',3) #fb: ['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa', 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc'] p('abc',2) #fb: ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc'] len(p("13579",3)) #fb: 125 edit() -- http://mail.python.org/mailman/listinfo/python-list