猿问

Python 协程在产量上给出未知无

我正在尝试根据用户输入构建一些数学运算的管道,并尝试打印该运算的累积结果。例如,输入将是一个操作列表,然后是数字输入的数量,然后是如下所示的数字:


[square, accumulate]

3

1

2

3

这应该返回如下内容:


1

5

14

首先,它将 1 打印为 1*1,然后将该 1 与 2*2 给出 5 的结果相加,然后将其添加到 3*3 中,给出 14。但是我的方法有问题,第二个数字输入总是变成None值,我不知道为什么。我被困在得到:


1

None

10

有什么想法吗?这是我的代码:


import math

import os

import random

import re

import sys


def printer():

    while True:

        x = yield

        print(x)


def co_generator(n):

    for _ in range(n):

        x = int(input())

        yield x


def get_root():

    while True:

        number = (yield)

        yield math.floor(math.sqrt(number))


def get_square():

    number = 0

    while True:

        number = (yield)

        yield number**2


def accumulator():

    acum = 0

    while True:

        acum += (yield)

        yield acum


def operations_pipeline(numbers, operations, print_acum):

    for num in numbers:

        for i, w in enumerate(operations):

            num = w.send(num)

        print_acum.send(num)

    for operation in operations:

        operation.close()

    print_acum.close()


if __name__ == '__main__':

    order = input().strip()

    n = int(input())


    numbers = co_generator(n)


    print_acum = printer()

    next(print_acum)


    root = get_root()

    next(root)


    accumulate = accumulator()

    next(accumulate)


    square = get_square()

    next(square)


    operations_pipeline(numbers, eval(order), print_acum)


长风秋雁
浏览 138回答 3
3回答

猛跑小猪

您正在编写代码,就好像接收值并发送值一样。这不是它的工作方式。所有收益都发送一个值并接收一个值。(yield)yield whatever当生成器执行时,它分两个阶段执行。首先,的参数成为当前或调用的返回值,生成器暂停执行。如果没有参数,则使用。这就是你的s来自哪里yieldyieldnextsendNoneNone其次,当执行另一个 或 时,生成器将取消暂停,并且参数(或者如果使用)将成为表达式的值。nextsendsendNonenextyield您正在尝试使用一个来接收参数,并使用另一个来设置 的返回值。你需要使用一个 single 来设置一个返回值并接收下一个 的参数。例如yieldsendsendyieldsendsenddef get_square():    number = 0    while True:        number = yield number**2或者,如果要使用单独的 s 在生成器端发送和接收值,则需要使用单独的(或)调用在另一端接收和发送值,并忽略 s。例如yieldsendnextNonew.send(num)num = next(w)而不是 ,所以看起来像num = w.send(num)operations_pipelinedef operations_pipeline(numbers, operations, print_acum):    for num in numbers:        for w in operations:            w.send(num)            num = next(w)        print_acum.send(num)    for operation in operations:        operation.close()    print_acum.close()

慕森卡

def rooter():    number=0    while True:        number= yield math.floor(math.sqrt(number))    def squarer():    number=0    while True:        number= yield number**2产量将给没有尝试这种方式def accumulator():    number=0    while True:        number+= yield number 

斯蒂芬大帝

我相信你需要在这里的代码中添加一个调用:nextoperations_pipelinedef operations_pipeline(numbers, operations, print_acum):&nbsp; &nbsp; for num in numbers:&nbsp; &nbsp; &nbsp; &nbsp; for i, w in enumerate(operations):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; num = w.send(num)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; next(w) # <<<--- this没有这个,我不相信它会回到第二次,假设你的第一个输入是。get_square[square, accumulate]
随时随地看视频慕课网APP

相关分类

Python
我要回答