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)
| 1 | class YieldResult(BaseException):pass |
| 2 | |
| 3 | def 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 |
no test coverage detected