Last active
March 21, 2019 15:08
-
-
Save tdhopper/41f3c5397bafdecf8869e24a02849a8d to your computer and use it in GitHub Desktop.
FizzBuzz on the Event Loop in Python 3.7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
import asyncio | |
from typing import List | |
async def sleepprint(i: int, s: str, end=" "): | |
await asyncio.sleep(i / 30) | |
print(s, end=end, flush=True) | |
async def fizz(i: int): | |
await sleepprint(i * 3, "Fizz", end="") | |
async def buzz(i: int): | |
await sleepprint(i * 5 + 0.3, "Buzz", end="") | |
async def linebreak(i: int): | |
await sleepprint(i + 0.7, "\n", end="") | |
async def count(i: int): | |
await sleepprint(i, str(i)) | |
async def fizzbuzz(): | |
# Create all coroutines before starting them | |
fizz_tasks = [asyncio.create_task(fizz(i)) for i in range(1, 101 // 3 + 1)] | |
buzz_tasks = [asyncio.create_task(buzz(i)) for i in range(1, 101 // 5 + 1)] | |
space_tasks = [asyncio.create_task(linebreak(i)) for i in range(1, 101)] | |
count_tasks = [ | |
asyncio.create_task(count(i)) for i in range(1, 101) if (i % 3) and (i % 5) | |
] | |
# Run coroutines | |
await asyncio.gather(*fizz_tasks, *buzz_tasks, *count_tasks, *space_tasks) | |
if __name__ == "__main__": | |
asyncio.run(fizzbuzz()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment