[Tutor] permutations?

Peter Otten __peter__ at web.de
Thu Dec 2 13:53:22 CET 2010


Alex Hall wrote:

> 1. Order matters; I meant to say that direction does not. That is, 123
> is not the same as 213, but 123 is the same as 321 since the second
> example is simply a reversal.
> 2. I am looking for all permutations and subpermutations (if that is a
> word) of 1-n where the list must have at least 2, but no more than n,
> unique numbers (so 1 is not valid, nor is 1231 since it repeats 1 and
> is too long for n=3).

>>> from itertools import permutations, chain
>>> def hall(items):
...     items = list(items)
...     maxwidth = len(items)
...     return chain.from_iterable(
...     (p for p in permutations(items, w) if p < p[::-1])
...     for w in range(2, maxwidth+1))
...
>>> map("".join, hall("123"))
['12', '13', '23', '123', '132', '213']
>>> map("".join, hall("111"))
[]

Is that it? Be warned though that normally you'll get duplicates if items 
repeat:

>>> map("".join, hall("112"))
['12', '12', '112', '112']

Peter



More information about the Tutor mailing list