# inside-out range function

William Clifford mr.william.clifford at gmail.com
Tue Apr 28 07:19:50 CEST 2009

On Apr 27, 9:22 pm, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> 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.htmlhttp://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.

Thanks for the links! Funny, while I worked on this I didn't think of
looking up card shuffling to see if there might be an algorithms for
it. I didn't think enrag (or her sister garne) would be unique, but I
didn't expect they could be useful either. Cool!

I weirder I needed was to generate an Ulam spiral sequence like this:

[4, 3, 2,
5, 0, 1,
7, 8, 9]

I found a couple of ways, one of which I'm a somewhat happier with.

--
William Clifford