interesting exercise

Michael Tobis mtobis at gmail.com
Mon May 7 23:45:52 EDT 2007


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




More information about the Python-list mailing list