This is related to question How to generate all permutations of a list in Python
How to generate all permutations that match following criteria: if
this is an implementation of onebyone's suggestion
from http://en.wikipedia.org/wiki/Permutation#Lexicographical_order_generation The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.
the function:
def perms(items):
items.sort()
yield items[:]
m = [len(items)-2] # step 1
while m:
i = m[-1]
j = [ j for j in range(i+1,len(items)) if items[j]>items[i] ][-1] # step 2
items[i], items[j] = items[j], items[i] # step 3
items[i+1:] = list(reversed(items[i+1:])) # step 4
if items
checking our work:
>>> foo=list(perms([1,3,2,4,5]))
>>> True in [(list(reversed(i)) in foo) for i in foo]
False