<div dir="ltr"><br><div class="gmail_extra"><br><div class="gmail_quote">2015-07-02 8:30 GMT+02:00 Pierre Quentel <span dir="ltr"><<a href="mailto:pierre.quentel@gmail.com" target="_blank">pierre.quentel@gmail.com</a>></span>:<br><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div dir="ltr">In languages such as Javascript, the incrementation of a for loop counter can be done by an operation, for instance :<br><br>for(i=1; i<N; i*=2)<br><br>would iterate on the powers of 2 lesser than N.<br><br>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 :<br><br>def gen(N):<br>    i = 1<br>    while i<=N:<br>        yield i<br>        i *= 2<br><br>then we can iterate on gen(N).<br><br>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 :<br><br>import operator<br><br>class Range:<br><br>    def __init__(self, start, stop, incrementor):<br>        self.start, self.stop = start, stop<br>        self.incrementor = incrementor<br>        # Function to compare current counter and stop value : <= or >=<br>        self.comp = <a href="http://operator.ge" target="_blank">operator.ge</a> if self.stop>self.start else operator.le<br>        self.counter = None<br>    <br>    def __iter__(self):<br>        return self<br>    <br>    def __next__(self):<br>        if self.counter is None:<br>            self.counter = self.start<br>        else:<br>            self.counter = self.incrementor(self.counter)<br>        if self.comp(self.counter, self.stop):<br>            raise StopIteration<br>        return self.counter<br><br>Iterating on the powers of 2 below N would be done by :<br><br>for i in Range(1, N, lambda x:x*2)<br><br>I haven't seen this discussed before, but I may not have searched enough. <br><br>Any opinions ?<br><br></div>
</blockquote></div><br></div><div class="gmail_extra">With the proposed Range class, here is an implementation of the Fibonacci sequence, limited to 2000 :<br><br>previous = 0<br>def fibo(last):<br>    global previous<br>    _next, previous = previous+last, last<br>    return _next<br><br>print(list(Range(1, 2000, fibo)))<br><br></div></div>