advent22/api/advent22_api/routers/_misc.py

32 lines
831 B
Python
Raw Normal View History

2022-10-14 22:47:16 +00:00
import itertools
import random
2022-10-14 23:21:14 +00:00
from typing import Any, Sequence
2022-10-14 22:47:16 +00:00
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()
2022-10-14 23:21:14 +00:00
async def get_rnd(bonus_salt: Any = "") -> random.Random:
loesungswort = await get_loesungswort()
return random.Random(f"{loesungswort}{bonus_salt}")
2022-10-14 22:47:16 +00:00
2022-10-14 23:03:36 +00:00
async def set_length(seq: Sequence, length: int) -> list:
2022-10-14 23:20:35 +00:00
# `seq` unendlich wiederholen
2022-10-14 23:03:36 +00:00
infinite = itertools.cycle(seq)
2022-10-14 23:20:35 +00:00
# Die ersten `length` einträge nehmen
2022-10-14 23:03:36 +00:00
return list(itertools.islice(infinite, length))
2022-10-14 22:47:16 +00:00
2022-10-14 23:21:14 +00:00
async def shuffle(seq: Sequence, rnd: random.Random | None = None) -> list:
2022-10-14 23:20:35 +00:00
# Zufallsgenerator
2022-10-14 23:21:14 +00:00
if rnd is None:
rnd = await get_rnd()
2022-10-14 23:20:35 +00:00
# Elemente mischen
2022-10-14 22:47:16 +00:00
return rnd.sample(seq, len(seq))