Python Monty大厅n门数

时间:2018-11-19 18:13:56

标签: python python-3.x

我有一个运行Monty Hall程序的模型,但我需要弄清楚如何向用户询问在这种情况下(藏身之处)的门数。仿真代码有效,这只是我需要帮助的开始部分。这是我到目前为止所拥有的,感谢您的提前帮助。

import random

#Ask the user for how many runs to simumlate

runs = int(input("How many games do you want to simulate?"))
switchwins, nonswitchwins, switchlosses, nonswitchlosses = 0, 0, 0, 0

# Get the random number started with a seed
random.seed()

#run once for user switching and once for user not switching
for swap in True,False:
# Do everything for the number of runs we have
for i in range(runs):
    #Ask the user for the number of hiding places which must be greater than 3
    while True:
        hidingplaces = int(input("This game requires 3 or more hiding places. How many would you like?"))
        if hidingplaces < 3:
        #return error 
            raise ValueError(f'doors must be greater than three, not {hidingplaces}')
        else: 
            break

    # All prizes are nothing apart from one which holds the coin
    prizes = ['nothing', 'nothing', 'coin']
    # Randomly mix them up
    random.shuffle(prizes)

    #select a random location
    ChoiceA = random.randrange(hidingplaces)

    # print("Before the prize is revealed, I will show you what is in one of the other hiding places")

    # remove one of the other hiding places which has nothing as a prize and isn't ChoiceA
    for currentlocation, contents in enumerate(prizes):
        if currentlocation != ChoiceA and contents == "nothing":
            showlocation = currentlocation
            # print("There is nothing in this location", showlocation)
            break


    if swap:
        #swap to the other location
        for currentlocation, contents in enumerate(prizes):
            if currentlocation != ChoiceA and currentlocation != showlocation:
                swap_to = currentlocation

        # check if the swapped choice is a win
        if prizes[swap_to] == "coin":
            switchwins +=1
        else: 
            switchlosses +=1
    # when not swapping locations check for win
    else:
        if prizes[ChoiceA] == "coin":
            nonswitchwins +=1
        else: 
            nonswitchlosses +=1

 print("This is the number of wins if the user switched", round((switchwins/runs)*100,1), "%")

 print("This is the number of wins if the user didn't switch", round((nonswitchwins/runs)*100,1),"%")

我得到的错误是:

IndexError                                Traceback (most recent call last)
<ipython-input-15-e7e700a3b515> in <module>()
     57         # when not swapping locations check for win
     58         else:
---> 59             if prizes[ChoiceA] == "coin":
     60                 nonswitchwins +=1
     61             else:

IndexError: list index out of range

2 个答案:

答案 0 :(得分:2)

毕竟,您要报告的问题与用户输入例程无关。这是因为您允许用户指定hidingplaces> 3,同时将列表prizes硬编码为正好具有3个条目。 ChoiceA(可以(随机)设置为小于hidingplaces的任何数字)用作prizes的索引。每当ChoiceA大于2时,就会引发您报告的异常。

解决此问题的策略可能包括(a)在定义hidingplaces的列表时使用prizes的值,或(b)使用ChoiceA % len(prizes)作为{{ 1}},而不只是prizes。请注意,这些对模拟的统计行为有不同的影响:正确的选择取决于您希望它如何表现。在ChoiceA现有定义旁边的注释中,该定义可能可能是您想要的:

prizes

答案 1 :(得分:1)

我已修复您的代码。我重写并简化了它,修复了一些语法错误,并修复了一些缩进错误。

检查代码中的注释。

编辑:我已修复代码。

def askDoors():
    '''
    Ask the user for the number of hiding places which must be greater than 3
    '''
    return int(input("This game requires 3 or more hiding places. How many would you like?"))

hidingplaces = askDoors()

while hidingplaces < 3:
    # return error
    print('Doors must be greater than three, not %d.' % hidingplaces)
    hidingplaces = askDoors()

print('Start.') # put game here (recommended to use a function)

编辑:对于第二个问题,只需将奖品更改为prizes = ['coin'],然后在其后添加即可。

for i in range(hidingplaces):
   prizes.append('nothing')