Arithmetic sequences in Python

Antoon Pardon apardon at forel.vub.ac.be
Wed Jan 18 04:12:31 EST 2006


Op 2006-01-16, Gregory Petrosyan schreef <gregory.petrosyan at gmail.com>:
> Please visit http://www.python.org/peps/pep-0204.html first.
>
> As you can see, PEP 204 was rejected, mostly because of not-so-obvious
> syntax. But IMO the idea behind this pep is very nice. So, maybe
> there's a reason to adopt slightly modified Haskell's syntax? Something
> like
>
> [1,3..10]  -->  [1,3,5,7,9]
> (1,3..10)  -->  same values as above, but return generator instead of
> list
> [1..10]     -->  [1,2,3,4,5,6,7,8,9,10]
> (1 ..)        -->  'infinite' generator that yield 1,2,3 and so on
> (-3,-5 ..)   -->  'infinite' generator that yield -3,-5,-7 and so on
>
> So,
> 1) "[]" means list, "()" means generator
> 2) the "start" is required, "step" and "end" are optional.
>
> Also, this can be nicely integrated with enumerations (if they will
> appear in python). Haskell is also example of such integration.

With some abuse of the language one can already do a number of things
in python2.4 now.

import sys
from types import SliceType

class vslice(object):

    def __init__(self, fun):
        self.fun = fun

    def __getitem__(self, inx):
        if not isinstance(inx, tuple):
          inx = inx,
        return self.fun(*inx)

@vslice
def rnglst(*arg):
    lst = []
    for el in arg:
        if type(el) is SliceType:
            start = el.start or 0
            stop = el.stop or sys.maxint
            step = el.step or 1
            if step > 0:
                while start < stop:
                    lst.append(start)
                    start += step
            else:
                while start > stop:
                    lst.append(start)
                    start += step
        else:
            lst.append(el)
    return lst
 
rnglst[3,4,5] --> [3, 4, 5]
rnglst[1, 2:8] --> [1, 2, 3, 4, 5, 6, 7]
rnglst[3:9:2, 21:6:-3] --> [3, 5, 7, 21, 18, 15, 12, 9]

-- 
Antoon Pardon




More information about the Python-list mailing list