inside-out range function

Paul Rubin http
Tue Apr 28 07:50:22 CEST 2009


William Clifford <mr.william.clifford at gmail.com> writes:
> def enrag(start, stop=None, step=1):
>     '''Yield a range of numbers from inside-out, evens on left.'''

    >>> list(enrag(10))
    [8, 6, 4, 2, 0, 1, 3, 5, 7, 9]    

ok, but:

    >>> list(enrag(10,20))
    [18, 16, 14, 12, 10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

is that really what you wanted?

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

For the 0...n-1 case, I think I'd write

    from itertools import chain
    def e(n):
        max_even = (n-1) & ~1
        return chain(xrange(max_even, -1, -2), xrange(1, n, 2))



More information about the Python-list mailing list