Created
May 23, 2024 03:36
-
-
Save mettler/ad672aa174437626eacac909b202bcc0 to your computer and use it in GitHub Desktop.
100 prisoners problem
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
import random | |
def create_boxes(): | |
""" Create a list of 100 boxes, each containing a unique number from 1 to 100. """ | |
numbers = list(range(1, 101)) | |
random.shuffle(numbers) | |
return numbers | |
def find_number(boxes, prisoner_number): | |
""" Simulate a prisoner trying to find their number using the loop strategy. """ | |
current_box = prisoner_number - 1 # Box index starts from 0 | |
for _ in range(50): | |
if boxes[current_box] == prisoner_number: | |
return True | |
current_box = boxes[current_box] - 1 | |
return False | |
def simulate_prisoners(): | |
""" Simulate all 100 prisoners trying to find their numbers. """ | |
boxes = create_boxes() | |
for prisoner_number in range(1, 101): | |
if not find_number(boxes, prisoner_number): | |
return False | |
return True | |
def run_simulations(n_simulations): | |
""" Run multiple simulations and calculate the success rate. """ | |
success_count = 0 | |
for _ in range(n_simulations): | |
if simulate_prisoners(): | |
success_count += 1 | |
return success_count / n_simulations | |
# Run 1000 simulations to estimate the success rate | |
n_simulations = 1000 | |
success_rate = run_simulations(n_simulations) | |
print(f"Success rate over {n_simulations} simulations: {success_rate:.2%}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment