I love how easy it is to implement all kinds of commonly used high-level algorithmic behavior in Python.
I am now looking for an optimal way of implementing recursive sequences or any other kind of generator whose next value depends on O(1) of the most recently generated previous values.
I.e. is it possible to implement the following reduceGenerator
in a single line (possibly using the existing reduce
function)?
Example
Generator
def reduceGenerator(f, iterable, initialValue):
it = iter(iterable)
value = initialValue
for x in it:
value = f(value, x)
yield value
Use case:
The following generates the sequence (a * s[i-1] + b) mod m
:
s = reduceGenerator(lambda prev, i: (a * prev + b) % m, range(N), s0)
s1 = next(s)
s2 = next(s)