Code:
from random import shuffle

n_prisoners = 100
max_attempts = 50


def simulate_one_run() -> bool:
    boxes = list(range(100))
    shuffle(boxes)

    for p in range(n_prisoners):
        key = boxes[p]
        n_opened = 1
        while key != p and n_opened < max_attempts:
            key = boxes[key]
            n_opened += 1

        if p != key:
            return False

    return True


n_run = 10000
n_successes = 0
for _ in range(n_run):
    is_success = simulate_one_run()
    if is_success:
        n_successes += 1

print(f"p(succès) = {n_successes / n_run}")
 
Last modified: Friday, 15 March 2024, 15:45