1

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)
Domi
  • 22,151
  • 15
  • 92
  • 122
  • Hmm, you can implement almost anything in a single line, but is it worth it? You already have a readable function here. Why do you want to squash it into a single line? – cs95 Jan 06 '19 at 07:08
  • You might be able to do a generator like `(value := f(value, x) for x in iterable)` using the very recently added *assignment expression* feature. – jasonharper Jan 06 '19 at 07:08
  • 1
    It already exists as [`itertools.accumulate`](https://docs.python.org/3/library/itertools.html#itertools.accumulate). – Dan D. Jan 06 '19 at 07:22
  • 1
    I don't think a generator function should return a final value. – Mike Robins Jan 06 '19 at 07:40
  • @coldspeed because we can! – Domi Jan 06 '19 at 17:50
  • @MikeRobins yeah, I also realized that the final `return` did not make any sense at all :) – Domi Jan 06 '19 at 17:50
  • @DanD. exactly what i'm looking for! Do you want to write an answer so I can accept it? – Domi Jan 06 '19 at 17:50
  • 2
    "can" and "should" are two different things... – cs95 Jan 06 '19 at 17:51
  • @coldspeed turns out that my curiosity for an alternate solution has yielded to me `accumulate`, a python native that I was not aware of. The way I see it, this question was worth asking. – Domi Jan 06 '19 at 17:57
  • Consider self-answering your question, with the solution you found! – cs95 Jan 06 '19 at 17:58
  • @coldspeed Credit goes to Dan D. Gonna wait for him to post the answer. Thanks for your encouragement and input! – Domi Jan 06 '19 at 17:59

0 Answers0