Last active
February 10, 2020 21:03
-
-
Save fridex/8a2442f7e187914af715968097688aa3 to your computer and use it in GitHub Desktop.
Pick a random item from a list, prioritize items with lower index.
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
#!/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() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A blog post explaining this gist is available on my blog.