From 71482983bf5e22d68117a357c9cde4d38f14a918 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn-Michael=20Miehe?= Date: Fri, 14 Oct 2022 22:47:16 +0000 Subject: [PATCH] shuffle funktion --- api/advent22_api/routers/_misc.py | 20 ++++++++++++++++++++ api/advent22_api/routers/days.py | 8 ++------ 2 files changed, 22 insertions(+), 6 deletions(-) create mode 100644 api/advent22_api/routers/_misc.py diff --git a/api/advent22_api/routers/_misc.py b/api/advent22_api/routers/_misc.py new file mode 100644 index 0000000..3700248 --- /dev/null +++ b/api/advent22_api/routers/_misc.py @@ -0,0 +1,20 @@ +import itertools +import random +from typing import Sequence + +from ..dav_common import dav_get_file + + +async def get_loesungswort() -> str: + fp = await dav_get_file("loesungswort.txt") + return fp.read().decode("utf8").strip() + + +async def shuffle(seq: Sequence, length: int | None = None) -> list: + rnd = random.Random(await get_loesungswort()) + + if length is not None: + infinity = itertools.cycle(seq) + seq = list(itertools.islice(infinity, length)) + + return rnd.sample(seq, len(seq)) diff --git a/api/advent22_api/routers/days.py b/api/advent22_api/routers/days.py index 9c3c7cc..5e85d96 100644 --- a/api/advent22_api/routers/days.py +++ b/api/advent22_api/routers/days.py @@ -10,21 +10,17 @@ from PIL import ImageDraw, ImageFont from ..dav_common import dav_get_file, dav_list_files from ._image import AdventImage +from ._misc import shuffle router = APIRouter(prefix="/days", tags=["days"]) loesungswort = "ABCDEFGHIJKLMNOPQRSTUVWX" -async def shuffle(string: str) -> str: - rnd = random.Random(loesungswort) - return "".join(rnd.sample(string, len(string))) - - @router.on_event("startup") async def startup() -> None: print(loesungswort) - print(await shuffle(loesungswort)) + print("".join(await shuffle(loesungswort))) @router.get("/letter/{index}")