[Python-ideas] Pass a function as the argument "step" of range()
pierre.quentel at gmail.com
Thu Jul 2 08:30:53 CEST 2015
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 :
i = 1
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
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
if self.counter is None:
self.counter = self.start
self.counter = self.incrementor(self.counter)
if self.comp(self.counter, self.stop):
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 ?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas