题目
用 send() 协议创建由多个协程组成的管道,对数据流依次过滤、变换和聚合。输入契约:待处理的数据项列表;输出契约:过滤与变换后的聚合结果。公开样例 [1, -2, 3, -4, 5](过滤正数、平方、求和)期望 35,即 1+9+25。隐藏测试覆盖空列表与全负数,均期望 0。
解题思路
每个阶段是一个无限循环的生成器协程,通过 yield 接收 send 传入的值;filter_positive 只把正数转发给下游,square_and_sum 累加平方。数据以推送方式流过管道,处理是惰性的,不需要一次性载入全部数据。
参考实现要点
@coroutine 装饰器先调用 next(cr) 预激协程,使其停在第一个 yield 等待数据。filter_positive(target) 收到 item 后若大于 0 就 target.send(item);square_and_sum 维护 total,并在循环中对每个 item 累加 item ** 2,参考代码在 item 为 None 时 yield total。示例的 35 来自对正数 1、3、5 求平方和。
常见错误
原文指出:忘记在发送数据前用 next(cr) 预激协程,会在第一次 send 时出现 StopIteration。另一个与边界有关的坑是输入为空或全为负数时没有数据进入聚合阶段,累计值应保持 0;需要显式发送结束哨兵再读取结果,否则会一直等待下一条数据。
验证方式
在 Python 3 中预激各阶段,依次 send 样例数据,最后发送 None 并读取累计值;分别测试空列表和全负数,确认结果为 0,并检查未预激时首次 send 的报错。
代码示例
def coroutine(func):
def wrapper(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return wrapper
@coroutine
def filter_positive(target):
while True:
item = yield
if item > 0:
target.send(item)
@coroutine
def square_and_sum():
total = 0
while True:
item = yield
total += item ** 2
if item is None:
yield total