Simple algorithm question - how to reorder a sequence economically

John Ladasky john_ladasky at sbcglobal.net
Fri May 24 13:33:47 EDT 2013


On Friday, May 24, 2013 3:52:18 AM UTC-7, Steven D'Aprano wrote:
> On Fri, 24 May 2013 01:14:45 -0700, Peter Brooks wrote:
> 
> > That is, for a sequence 1,2,3,4 to produce an arbitrary ordering (eg
> > 2,1,4,3) that is different each time.
> 
> You can't *guarantee* that it will be different each time. 

Well, within limits, you can guarantee a LONG TIME between repeats.  And that may be good enough for Peter's purpose. 

When the number of elements in your sequence is short enough (the right value of "short enough" is at least partially a matter of opinion, and the amount of RAM available, but I would guess n < 10 myself), use itertools.permutations to generate all the possibilities at once -- call this list p.  Store p in memory.  Then shuffle p, and use its elements one at a time.  If you get to the end of p and need to keep working, it's up to you whether to shuffle p a second time.  If you don't reshuffle p, it guarantees the maximum interval between reusing the same permutation.

Use random.shuffle on your sequence directly, when your sequence has a larger number of elements.  This doesn't guarantee that two successive permutations will not be identical, but the probability is of course very low.



More information about the Python-list mailing list