Question: Take a look at the code below. #!/usr/bin/env python3 # chained.py import asyncio import random import time async def part1(n: int) -> str: i =

Take a look at the code below.

 #!/usr/bin/env python3 # chained.py import asyncio import random import time async def part1(n: int) -> str: i = random.randint(0, 10) print(f"part1({n}) sleeping for {i} seconds.") await asyncio.sleep(i) result = f"result{n}-1" print(f"Returning part1({n}) == {result}.") return result async def part2(n: int, arg: str) -> str: i = random.randint(0, 10) print(f"part2{n, arg} sleeping for {i} seconds.") await asyncio.sleep(i) result = f"result{n}-2 derived from {arg}" print(f"Returning part2{n, arg} == {result}.") return result async def chain(n: int) -> None: start = time.perf_counter() p1 = await part1(n) p2 = await part2(n, p1) end = time.perf_counter() - start print(f"-->Chained result{n} => {p2} (took {end:0.2f} seconds).") async def main(*args): await asyncio.gather(*(chain(n) for n in args)) if __name__ == "__main__": import sys random.seed(444) args = [1, 2, 3] if len(sys.argv) == 1 else map(int, sys.argv[1:]) start = time.perf_counter() asyncio.run(main(*args)) end = time.perf_counter() - start print(f"Program finished in {end:0.2f} seconds.")

Modify the above program so that the names of the events become strings instead of integers. A sample output is given below.

$ python3 chained.py A B C
part1(A) sleeping for 4 seconds. part1(B) sleeping for 4 seconds. part1(C) sleeping for 0 seconds. Returning part1(C) == result3-1. part2('C', 'resultC-1') sleeping for 4 seconds. Returning part1(A) == result9-1. part2('A', 'resultA-1') sleeping for 7 seconds. Returning part1(B) == result6-1. part2('B', 'resultB-1') sleeping for 4 seconds. Returning part2('C', 'resultC-1') == resultC-2 derived from resultC-1. -->Chained resultC => resultC-2 derived from resultC-1 (took 4.02 seconds). Returning part2('B', 'resultB-1') == resultB-2 derived from resultB-1. -->Chained resultB => resultB-2 derived from resultB-1 (took 8.02 seconds). Returning part2('A', 'resultA-1') == resultA-2 derived from resultA-1. -->Chained resultA => resultA-2 derived from resultA-1 (took 11.03 seconds). Program finished in 11.03 seconds.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!