0

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
3
  • 2
    order.sort() works.. Commented Jan 28, 2014 at 11:46
  • 2
    Do you want all the rotations or all the permutations? Commented Jan 28, 2014 at 11:48
  • 1
    Do you want to produce all possible permutations or you want to find A particular one and stop the search there? Commented Jan 28, 2014 at 11:57

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

[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.
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!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.