Skip to content

Instantly share code, notes, and snippets.

@barrucadu
Created September 2, 2024 11:32
Show Gist options
  • Save barrucadu/88bd2f4a8831c04fda0678d35ce4e7be to your computer and use it in GitHub Desktop.
Save barrucadu/88bd2f4a8831c04fda0678d35ce4e7be to your computer and use it in GitHub Desktop.
# 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