full-speed-python习题解答(八)-- Coroutines

本文深入探讨了Python中协同(coroutines)的应用,通过实例演示了如何创建并使用协同来处理数据,包括计算数值平方、跟踪最小值及最大值,并实现了一个生产者-消费者管道,展示了协同在数据处理和流控制中的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python协同(coroutines)类似于生成器,会使用yield关键字,但它不是生成数据,而是通常消费(consume)数据。

Exercise with coroutines

1. Create a coroutine named “square” that prints the square of any sent value.

def square():
    print('square')
    while True:
        val = yield
        print(val*val)

s=square()
next(s)
s.send(2)
s.send(3)
s.send(4)
s.close()
s.send(5)

2. Implement the “minimize” coroutine that keeps and prints the minimum value that is sent to the function.

def minimize():
    print("minimize")
    var = yield
    min = var
    print('min',min)
    while True:
        curr = yield
        if min>=curr:
            min=curr
        print("min",min)

m = minimize()
next(m)
m.send(3)
m.send(2)
m.send(5)

Exercise with coroutines

1. Implement a producer-consumer pipeline where the values squared by the producer are sent to two consumers. One should store and print the minimum value sent so far and the other the maximum value.

def producer(consumers):
    print('producer ready')
    try:
        while True:
            var = yield
            for consumer in consumers:
                consumer.send(var*var)
    except GeneratorExit:
        for consumer in consumers:
            consumer.close()

def consumer(name,func):
    print(f"{name} ready")
    var = yield
    max = var
    min = var
    print(f"current {func} value is {var}")
    
    try:
        while True:
            curr = yield
            if func == "max":
                if max<=curr:
                    max=curr
                print(f"current max value is {max}")
            else:
                if min>=curr:
                    min=curr
                print(f"current min value is {min}")
    except GeneratorExit:
        print(f"{name} closed")

conmax = consumer("conmax","max")
conmin = consumer("conmin","min")
proc = producer([conmax,conmin])

next(conmax)
next(conmin)
next(proc)

proc.send(1)
proc.send(2)
proc.send(5)
proc.send(0)

2. Implement a producer-consumer pipeline where the values squared by the producer are dispatched to two consumers, one at a time. The first value should be sent to consumer 1, the second value to consumer 2, third value to consumer 1 again, and so on. Closing the producer should force the consumers to print a list with the numbers that each one obtained.

def turn_on(label):
    if label==1:
        return 0
    elif label==0:
        return 1
def producer(consumers):
    print("producer ready")
    try:
        index = 0
        while True:
            var = yield
            consumers[index].send(var*var)
            index = turn_on(index)
    except GeneratorExit:
        for consumer in consumers:
            consumer.close()
list=[[] for i in range(2)]
def consumer(name,label):
    print(f"{name} ready")
    
    try:
        while True:
                var = yield
                list[label].append(var)
                print(f"consumer{label+1}",var)
                
    except GeneratorExit:
        print(f"consumer{label+1}",list[label])
        

con1 = consumer("consumer1",0)
con2 = consumer("consumer2",1)
prod = producer([con1,con2])

next(con1)
next(con2)
next(prod)

prod.send(1)
prod.send(2)
prod.send(3)
prod.send(4)
prod.close()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值