[Python-ideas] Pass a function as the argument "step" of range()

Pierre Quentel pierre.quentel at gmail.com
Fri Jul 3 09:30:15 CEST 2015


2015-07-02 8:30 GMT+02:00 Pierre Quentel <pierre.quentel at gmail.com>:

> In languages such as Javascript, the incrementation of a for loop counter
> can be done by an operation, for instance :
>
> for(i=1; i<N; i*=2)
>
> would iterate on the powers of 2 lesser than N.
>
> To achieve the same thing in Python we currently can't use range() because
> it increments by an integer (the argument "step"). An option is to build a
> generator like :
>
> def gen(N):
>     i = 1
>     while i<=N:
>         yield i
>         i *= 2
>
> then we can iterate on gen(N).
>
> My proposal is that besides an integer, range() would accept a function as
> the "step" argument, taking the current counter as its argument and
> returning the new counter value. Here is a basic pure-Python implementation
> :
>
> import operator
>
> class Range:
>
>     def __init__(self, start, stop, incrementor):
>         self.start, self.stop = start, stop
>         self.incrementor = incrementor
>         # Function to compare current counter and stop value : <= or >=
>         self.comp = operator.ge if self.stop>self.start else operator.le
>         self.counter = None
>
>     def __iter__(self):
>         return self
>
>     def __next__(self):
>         if self.counter is None:
>             self.counter = self.start
>         else:
>             self.counter = self.incrementor(self.counter)
>         if self.comp(self.counter, self.stop):
>             raise StopIteration
>         return self.counter
>
> Iterating on the powers of 2 below N would be done by :
>
> for i in Range(1, N, lambda x:x*2)
>
> I haven't seen this discussed before, but I may not have searched enough.
>
> Any opinions ?
>
>
With the proposed Range class, here is an implementation of the Fibonacci
sequence, limited to 2000 :

previous = 0
def fibo(last):
    global previous
    _next, previous = previous+last, last
    return _next

print(list(Range(1, 2000, fibo)))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150703/b7ca116c/attachment.html>


More information about the Python-ideas mailing list