Created
September 2, 2024 11:32
-
-
Save barrucadu/88bd2f4a8831c04fda0678d35ce4e7be to your computer and use it in GitHub Desktop.
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
# pyrite: strict | |
import typing | |
import random | |
T = typing.TypeVar("T") | |
def weighted_choice(freqdict: dict[T, int]) -> T: | |
items = freqdict.items() | |
# why is this line ok? random.choices will return `None` if `items` is empty - this | |
# is exactly the sort of error I'd expect a type checker to catch! | |
return random.choices([k for k, _ in items], weights=[w for _, w in items])[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment