inside-out range function

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Apr 28 06:22:07 CEST 2009


On Mon, 27 Apr 2009 20:27:07 -0700, William Clifford wrote:

> For some reason I thought I needed this code, but it turns out I don't,
> really.
> I need something weirder. Anyway, maybe someone else could use this.
> 
> def enrag(start, stop=None, step=1):
>     '''Yield a range of numbers from inside-out, evens on left.'''
[snip code]

Interesting.

That's equivalent to a reverse followed by a Monge Shuffle.

http://mathworld.wolfram.com/MongesShuffle.html
http://en.wikipedia.org/wiki/Shuffling_playing_cards#Mongean_shuffle


I wrote a similar function to do this:

def monge_shuffle(deck):
    if len(deck) % 2: # Odd number of items.
        deck[:] = deck[0::2] + deck[1::2][::-1]
    else: # Even number of items.
        deck[:] = deck[1::2] + deck[0::2][::-1]
    return deck

>>> list(enrag(20))
[18, 16, 14, 12, 10, 8, 6, 4, 2, 0, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> monge_shuffle(range(20)[::-1])
[18, 16, 14, 12, 10, 8, 6, 4, 2, 0, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> list(enrag(203)) == monge_shuffle(range(203)[::-1])
True



I'm curious what your "something weirder" was.



-- 
Steven




More information about the Python-list mailing list