Skip to content

Instantly share code, notes, and snippets.

@tdhopper
Last active March 21, 2019 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdhopper/41f3c5397bafdecf8869e24a02849a8d to your computer and use it in GitHub Desktop.
Save tdhopper/41f3c5397bafdecf8869e24a02849a8d to your computer and use it in GitHub Desktop.
FizzBuzz on the Event Loop in Python 3.7
#!/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