[Python-ideas] Pass a function as the argument "step" of range()
pierre.quentel at gmail.com
Thu Jul 2 17:16:01 CEST 2015
2015-07-02 16:02 GMT+02:00 Nick Coghlan <ncoghlan at gmail.com>:
> On 2 July 2015 at 17:12, Nathaniel Smith <njs at pobox.com> wrote:
> > This isn't going to work for range() anyway though AFAICT because range
> > isn't an iterator, it's an iterable that offers O(1) membership tests.
> Right, Python 3's range() is best thought of as a memory-efficient
> tuple, rather than as an iterator like Python 2's xrange().
> As far as the original request goes, srisyadasti's answer to the
> Reddit thread highlights one reasonable answer: encapsulating the
> non-standard iteration logic in a reusable generator, rather than
> making it easier to define non-standard logic inline. That feature
> wasn't copied from C into Python for loops, so there's no reason to
> copy it from Java either.
> In addition to writing a custom generator, or nesting a generator
> expression, it's also fairly straightforward to address the OP's
> request by way of map() and changing the expression of the limiting
> factor (to be the final input value rather than the final output
> def calc_value(x):
> return 2 ** (x + 1)
> for i in map(calc_value, range(10)):
Again, this does not address the original problem : it produces the first
10 squares of 2, not the squares of 2 lower than a "stop" value.
The logic of range(start, stop, step) is to produce the integers starting
at "start", incremented by "step", until the integer is >= "stop" (or <=
stop if stop<start).
In simple cases you can probably compute the number of iterations in
advance (that's what some answers in the reddit discussion did with
logarithms), but it won't be so easy for more complex series ; you can also
test the stop condition in the generator (this is what I did in my
contribution as "kervarker") ; but I think it would be better to stick to
the logic of range() with a more general incrementation method.
> Depending on the problem being solved, "calc_value" could hopefully be
> given a more self-documenting name.
> Given the kinds of options available, the appropriate design is likely
> to come down to the desired "unit of reusability".
> * iteration pattern reusable as a whole? Write a custom generator
> * derivation of iteration value from loop index reusable? Write a
> derivation function and use map
> * one-shot operation? Use an inline generator expression or a break
> inside the loop
> Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
> Python-ideas mailing list
> Python-ideas at python.org
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas