[Python-ideas] Pass a function as the argument "step" of range()
Paul Moore
p.f.moore at gmail.com
Sat Jul 4 22:33:43 CEST 2015
On 4 July 2015 at 14:48, Nick Coghlan <ncoghlan at gmail.com> wrote:
> 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.
Ah, thanks. I hadn't thought of using accumulate with a function that
ignored its second argument.
Although the above seems noticeably less obvious than my hand-coded
def iterate(fn, start):
while True:
yield start
start = fn(start)
Unless the accumulate version is substantially faster (I haven't
tested), I can't imagine ever wanting to use it in preference.
Paul
More information about the Python-ideas
mailing list