并发算一批的结果

👁️ 3 人浏览 💬 0 人评论 ❤️ 添加收藏

(每道题开头都有同一段:square(x) 是个协程,里面 await asyncio.sleep(0) 让出控制再返回 x*x;run_list(xs) 用 asyncio.gather 并发算每个的平方、按提交顺序回列表;run_sum 交回结果之和。判题机自带 asyncio。)

并发算 1、2、3 的平方,打印结果列表:

import asyncio


async def square(x):
    await asyncio.sleep(0)          # 在这里让出控制(不引入真实时长)
    return x * x


async def _gather(xs):
    return await asyncio.gather(*[square(x) for x in xs])


def run_list(xs):
    """并发算每个数的平方,交回结果列表(gather 按提交顺序回,确定)。"""
    return asyncio.run(_gather(xs))


def run_sum(xs):
    """并发算每个数的平方,交回结果之和(和与顺序无关,确定)。"""
    return sum(asyncio.run(_gather(xs)))

print(",".join(str(x) for x in run_list([1, 2, 3])))
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论