interesting exercise

castironpi at gmail.com castironpi at gmail.com
Tue May 8 00:46:07 EDT 2007


On May 7, 11:42 pm, castiro... at gmail.com wrote:
> On May 7, 11:34 pm, castiro... at gmail.com wrote:
>
>
>
> > On May 7, 10:45 pm, Michael Tobis <mto... at gmail.com> 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.
> [working solution snip]

Or even,
def p(a,b):
	if list( a ) != sorted( list( a ) ): raise ValueError, "String not
ordered."
	if not b: return ['']
	return [i+j for i in list(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()




More information about the Python-list mailing list