MCPcopy Create free account
hub / github.com/ActiveState/code / greduce

Function greduce

recipes/Python/498264_reduce_as_a_generator/recipe-498264.py:3–32  ·  view source on GitHub ↗

Reduce generator. @param func: function of two arguments. Unlike reduce the function passed into the generator may not need to return a value but modify its first argument inplace like list.extend. @param strm: list of values passed into func. strm

(func, strm)

Source from the content-addressed store, hash-verified

1class YieldResult(BaseException):pass
2
3def greduce(func, strm):
4 '''
5 Reduce generator.
6 @param func: function of two arguments. Unlike reduce the function passed
7 into the generator may not need to return a value but modify
8 its first argument inplace like list.extend.
9 @param strm: list of values passed into func. strm can be updated using
10 greduce.send(l) where l is another list.
11 '''
12 res = None
13 while 1:
14 try:
15 try:
16 if res is None:
17 res, v = strm[:2]
18 del strm[0:2]
19 else:
20 v = strm[0]
21 del strm[0]
22 except (ValueError, IndexError):
23 l = yield
24 else:
25 out = func(res, v)
26 res = out if out is not None else res
27 l = yield res
28 if l:
29 strm.extend(l)
30 yield
31 except YieldResult:
32 yield res
33
34
35

Callers 1

recipe-498264.pyFile · 0.85

Calls 2

funcFunction · 0.50
extendMethod · 0.45

Tested by

no test coverage detected