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

Nick Coghlan ncoghlan at gmail.com
Sat Jul 4 15:48:48 CEST 2015


On 4 July 2015 at 20:56, Paul Moore <p.f.moore at gmail.com> wrote:
> On 4 July 2015 at 00:53, Andrew Barnert via Python-ideas
> <python-ideas at python.org> wrote:
>> Also, this has the same problem as many of the other proposed solutions, in that it assumes that you can transform the iterative n*2 into an analytic 2**n, and that you can work out the maximum domain value (10) in your head from the maximum range value (1000), and that both of those transformations will be obvious to the readers of the code. In this particular trivial case, that's true, but it's hard to imagine any real-life case where it would be.
>
> One thing that I have kept stumbling over when I've been reading this
> discussion is that I keep expecting there to be a "simple" (i.e.,
> builtin, or in a relatively obvious module) way of generating repeated
> applications of a single-argument function:
>
>     def iterate(fn, start):
>         while True:
>             yield start
>             start = fn)start)
>
> ... and yet I can't find one. Am I missing it, or does it not exist?
> It's not hard to write, as shown above, so I'm not claiming it "needs
> to be a builtin" necessarily, it just seems like a useful building
> block.

It's a particular way of using itertools.accumulate:

    def infinite_series(fn, start):
        def series_step(last_output, __):
            return fn(last_output)
        return accumulate(repeat(start), series_step)

Due to the closure, that can be generalised to tracking multiple past
values fairly easily (e.g. using deque), and the use of repeat() means
you can adapt it to define finite iterators as well.

This is covered in the accumulate docs
(https://docs.python.org/3/library/itertools.html#itertools.accumulate)
under the name "recurrence relation", but it may be worth extracting
the infinite series example as a new recipe in the recipes section.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list