Created
August 5, 2018 15:46
-
-
Save jounderwood/bc8e19e28109812d9b471d30d702501b to your computer and use it in GitHub Desktop.
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 python3 | |
| # https://en.wikipedia.org/wiki/Monty_Hall_problem | |
| # Monty Hall problem simulation | |
| import random | |
| import sys | |
| BOXES_COUNT = 3 | |
| DEFAULT_EXPERIMENTS_COUNT = 1000 | |
| def not_change_decision(): | |
| boxes = [0] * BOXES_COUNT | |
| boxes[random.randint(0, BOXES_COUNT - 1)] = 1 | |
| has_prise = bool(random.choice(boxes)) | |
| return has_prise | |
| def change_decision(): | |
| boxes = [0] * BOXES_COUNT | |
| boxes_indexes = list(range(BOXES_COUNT)) | |
| boxes[random.choice(boxes_indexes)] = 1 | |
| initially_chosen_box_index = random.choice(boxes_indexes) | |
| another_boxes_indexes = [i for i in boxes_indexes if i != initially_chosen_box_index] | |
| another_empty_boxes_indexes = [i for i in another_boxes_indexes if not boxes[i]] | |
| another_boxes_indexes.remove(random.choice(another_empty_boxes_indexes)) | |
| chosen_box_index = random.choice(another_boxes_indexes) | |
| has_prise = bool(boxes[chosen_box_index]) | |
| return has_prise | |
| def main(): | |
| try: | |
| experiments_count = int(sys.argv[1]) | |
| except IndexError: | |
| experiments_count = DEFAULT_EXPERIMENTS_COUNT | |
| for experiment in (not_change_decision, change_decision): | |
| wins_count = 0 | |
| for i in range(experiments_count): | |
| wins_count += int(experiment()) | |
| print(experiment.__name__, wins_count / experiments_count) | |
| if __name__ == '__main__': | |
| main() | |
| # not_change_decision 0.3363 | |
| # change_decision 0.6652 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment