Get Out Of Jail

Python Puzzles

Back to the Python! homepage


You are locked in a jail cell and demand to be released because you are innocent. The warden tells you he will release you if you can win 2 straight games of checkers. But you must play at least one game against the warden and one game against the sheriff. You know the sheriff plays a better game of checkers than the warden.

Do you have a better probability of winning if you play [Warden -> Sheriff -> Warden] or [Sheriff -> Warden -> Sheriff]? Remember, the sheriff is a better checkers player than the warden, and you must win 2 straight games.


You are more likely to win 2 straight games playing [Sheriff -> Warden -> Sheriff].

The probability changes depending on the variables you set for the warden and the sheriff. But given you must win the second game to get out of jail, it is best to play the weaker opponent second and hope you can win 1 of 2 from the more challenging opponent.

import numpy as np

# Sheriff's and warden's win probabilities
sheriff = .75
warden = .5

# List to hold the number of scenarios where Sheriff wins in each game
scenario1 = []

# List to hold the number of scenarios where warden wins in each game
scenario2 = []

# Loop through 1 million games
for _ in range(1_000_000):

    # Game scenario: sheriff -> warden -> sheriff
    winning_count = 0

    # Play 1
    sheriff_play1 = np.random.binomial(1, sheriff, 1).item()
    winning_count += 1 if sheriff_play1 == 0 else winning_count

    # Play 2
    warden_play1 = np.random.binomial(1, warden, 1).item()
    winning_count = winning_count + 1 if warden_play1 == 0 else 0

    # If Sheriff wins 2 out of 3 plays, add 1 to scenario1
    if winning_count == 2:
        scenario1.append(1)

    # Play 3
    sheriff_play2 = np.random.binomial(1, sheriff, 1).item()
    winning_count = winning_count + 1 if sheriff_play2 == 0 else 0

    # If Sheriff wins 2 out of 3 plays, add 1 to scenario1
    if winning_count >= 2:
        scenario1.append(1)

    # Game scenario: sheriff -> warden -> sheriff
    winning_count = 0

    # Play 1
    warden_play1 = np.random.binomial(1, warden, 1).item()
    winning_count += 1 if warden_play1 == 0 else winning_count

    # Play 2
    sheriff_play1 = np.random.binomial(1, sheriff, 1).item()
    winning_count = winning_count + 1 if sheriff_play1 == 0 else 0

    # If Sheriff wins 2 out of 3 plays, add 1 to scenario2
    if winning_count == 2:
        scenario2.append(1)
        winning_count = 0

    # Play 3
    warden_play2 = np.random.binomial(1, warden, 1).item()
    winning_count = winning_count + 1 if warden_play2 == 0 else 0

    # If Sheriff wins 2 out of 3 plays, add 1 to scenario2
    if winning_count >= 2:
        scenario2.append(1)

# Print the number of scenarios where Sheriff wins in each game
print("Number of scenarios where Sheriff wins (scenario1):", len(scenario1))
print("Number of scenarios where Sheriff wins (scenario2):", len(scenario2))