Skip to content

Instantly share code, notes, and snippets.

@fridex
Last active February 10, 2020 21:03
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 fridex/8a2442f7e187914af715968097688aa3 to your computer and use it in GitHub Desktop.
Save fridex/8a2442f7e187914af715968097688aa3 to your computer and use it in GitHub Desktop.
Pick a random item from a list, prioritize items with lower index.
#!/usr/bin/env python3
import math
import random
import sys
def random_termial(n: int) -> int:
"""Get index to an item from a list of size n.
The higher index of an item is, the lower probability of picking it.
"""
assert n >= 1
termial_of_n = ((n**2) + n) >> 1
choice = random.randrange(termial_of_n)
i = math.floor(-0.5 + math.sqrt(0.25 + (choice << 1)))
return n - 1 - i
def main() -> None:
if len(sys.argv) == 1:
print(f"Usage: {sys.argv[0]} [N..]", file=sys.stderr)
sys.exit(1)
for item in sys.argv[1:]:
n = int(item) # Any exception reported.
res = random_termial(n)
print(f"Random index using random termial to a list of size {n} is {res}")
__name__ == "__main__" and main()
@fridex
Copy link
Author

fridex commented Feb 10, 2020

A blog post explaining this gist is available on my blog.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment