I want to sort an array, so it starts off at
order = [0,1,2,3,4,5] #loop around trying all columns`
and then will go through, trying all combinations of this so 1,2,3,4,5,0 etc, and stop once it has tried all of them.
Is there anyway to do this in python?
asked Jan 28, 2014 at 11:43
user2065929
1,1154 gold badges22 silver badges35 bronze badges
2 Answers 2
If you just want to "rotate" a list, have a look at the deque class:
>>> from collections import deque
>>> order = [0,1,2,3,4,5]
>>> order.sort() # ensure order is sorted
>>> q = deque(order)
>>> for _ in xrange(len(q)):
... q.rotate(-1)
... print q
...
deque([1, 2, 3, 4, 5, 0])
deque([2, 3, 4, 5, 0, 1])
deque([3, 4, 5, 0, 1, 2])
deque([4, 5, 0, 1, 2, 3])
deque([5, 0, 1, 2, 3, 4])
deque([0, 1, 2, 3, 4, 5])
>>>
answered Jan 28, 2014 at 11:46
sloth
101k21 gold badges183 silver badges224 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
If you mean all permutations, rather than the rotations in Dominic's answer:
import itertools
permutations = [ p for p in itertools.permutations(order) ]
There's 720 permutations in total so I won't print them :)
answered Jan 28, 2014 at 11:51
James Little
2,06914 silver badges12 bronze badges
2 Comments
André Laszlo
[p for p in <iterable>] <==> list(<iterable>) Converting an iterator to a list can be very expensive, especially for permutations, which would consume O(n!) memory. Yikes.James Little
Sure, depending on what he wants to do with the permutations, he may not need them stored in a list. In which case much better to iterate over itertools.permutations(order) directly. Good point!
lang-py
order.sort()works..rotationsor all thepermutations?