[Python] Why does my code give not the expected value at the prisoners problem?

Discussão em 'Python' iniciado por Stack, Março 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have a question about the "Prisoners Problem" and my tackeling of that. I made a little Project simulating it in Python, and the results I'm getting are not what I was expecting. I'm getting around a 45-55% succsessrate, while the blank math gets a round about 33% succsessrate.

    Here is my Code for that:

    def GenerateBoxes():
    import random
    from random import sample

    # Generate a list of 100 unique random numbers between 1 and 100
    random_values = sample(range(1, 101), 100)

    # Create a dictionary (boxes) with 100 different keys and the generated random values
    boxes = {i: value for i, value in enumerate(random_values, start=1)}

    return boxes




    def SimulateExperiment(timesGiven):

    # a list of wether the 100 prisoners escape or not, represented as a bool
    sucsesses = []

    # how often the experiment should be repeated
    times = timesGiven
    x = 0
    while x < times:
    boxes = GenerateBoxes()
    escape = True;

    p_num = 1
    temp_p_num = 1
    for p_num in range(1, 100):
    k = 1
    while k < 100:
    if k <= 50 and temp_p_num == boxes[p_num]:
    break
    elif k > 50 and temp_p_num == boxes[p_num]:
    escape = False
    break
    else:
    temp_p_num = boxes[temp_p_num]
    k += 1

    p_num += 1

    if escape == True:
    sucsesses.append(x)

    x += 1

    return sucsesses

    times = 100000

    sucsessrate = SimulateExperiment(times)
    sucsessPercent = (len(sucsessrate) / times) * 100
    print( "Sucsessrate: " + len(sucsessrate).__str__() + " out of " + times.__str__() + ": " + sucsessPercent.__str__() + "%")


    Do I have a thinking error or why do I get different results?

    Thank you for reading!

    Continue reading...

Compartilhe esta Página