Last active
January 13, 2021 19:13
-
-
Save sonnyksimon/227927589b8dbbf2cd35416079cbff0c to your computer and use it in GitHub Desktop.
Calculate the probability of atleast one match after x tries
This file contains hidden or 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 python | |
# -*- coding: utf-8 -*- | |
# | |
# SPDX-License-Identifier: MIT | |
# | |
""" Calculate the probability of atleast one match after x tries""" | |
from __future__ import print_function | |
import argparse | |
import sys | |
def probability(options): | |
percent_value = float(options.percent) | |
# Probability of getting a match after 1 try | |
fractional_value = percent_value/100 | |
# Not a match after 1 try | |
no_match_fractional_value = 1 - fractional_value | |
# No of tries | |
num_tries = 0 | |
while True: | |
# No matches after `num_tries` tries | |
no_matches_fractional_value = no_match_fractional_value ** num_tries | |
num_tries += 1 | |
# At least one match after `num_tries` tries | |
one_match_fractional_value = 1 - no_matches_fractional_value | |
one_match_percent_value = 100 * one_match_fractional_value | |
rounded_match_percent_value = round(one_match_percent_value) | |
print(f"Tries: {str(num_tries).rjust(3,'0')}; Probability: {rounded_match_percent_value}%") | |
if rounded_match_percent_value >= 100: | |
break | |
return ScriptRC.SUCCESS | |
def get_options(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-p", "--percent", action="store", help="Percentage value", type=float, required=True) | |
return parser.parse_args() | |
class ScriptRC(object): | |
"""Enum for script return codes""" | |
SUCCESS = 0 | |
FAILURE = 1 | |
EXCEPTION = 2 | |
class ScriptException(Exception): | |
pass | |
if __name__ == "__main__": | |
# Get the options from the user | |
options = get_options() | |
# Run main script | |
try: | |
rc = probability(options) | |
except Exception as e: | |
rc = ScriptRC.EXCEPTION | |
sys.exit(rc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment