interesting exercise
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Tue May 8 00:21:37 EDT 2007
En Tue, 08 May 2007 00:45:52 -0300, Michael Tobis <mtobis at gmail.com>
escribió:
> 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.
This is what I come, no tricks, no special optimizations, just plain
Python (including your constraints):
def permute(values, n):
def _permute(values, n):
if n==1:
for letter in values:
yield [letter]
else:
for letter in values:
for others in _permute(values, n-1):
yield [letter]+others
if not sorted(values): raise ValueError("unsorted values")
if len(set(values))!=len(values): raise ValueError("duplicate values")
return list(''.join(item) for item in _permute(values, n))
--
Gabriel Genellina
More information about the Python-list
mailing list