例程在每个替代迭代中均返回None

问题描述 投票:0回答:1

我有一段代码,如下所示:

#!/bin/python3

import math
import os
import random
import re
import sys
import logging


def consumer():
    while True:
        x = yield
        print(x)

def producer(n):
    for _ in range(n):
        x = int(input())
        yield x


def rooter():
    logging.info("Running the rooter")
    while True:
        value = (yield)
        yield math.sqrt(value)


def squarer():
    logging.info("Running the squarer")
    while True:
        value = (yield)
        print("from squarer: {}".format(value))
        yield value * value


def accumulator():
    logging.info("Running the accumulator.")
    running_total = 0
    while True:
        value = (yield)
        running_total += value
        yield running_total


def pipeline(prod, workers, cons):
    logging.info("workers: {}".format(workers))
    for num in prod:
        for i, w in enumerate(workers):
            num = w.send(num)
        cons.send(num)
    for worker in workers:
        worker.close()
    cons.close()

if __name__ == '__main__':
    order = input().strip()
    m = int(input())

    prod = producer(m)

    cons = consumer()
    next(cons)

    root = rooter()
    next(root)

    accumulate = accumulator()
    next(accumulate)

    square = squarer()
    next(square)

    pipeline(prod, eval(order), cons)

样本输入

[square, accumulate]
3  <- Number of inputs coming further

1  <- actual inputs
2
3

样本输出

*The output should be as below:*
1
5
14

但是1013的平方和)实际应为14123的平方和)

因此,实际上缺少输入2(在输入行中是第二个)。在进一步调试时,我发现每个替代迭代都是这种情况,而不仅仅是此处提供的输入。

我无法解读正在发生的事情。如果有帮助,协程squarer是第二次迭代中返回None的程序。我将不胜感激。

python-3.x yield coroutinescope
1个回答
0
投票

我找到了解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.