我们做笔交易吧

2024-09-26 22:52:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个基于旧电视节目的python程序,让我们达成协议。我让程序打印出游戏的数量,以及用户是否应该切换或留下。现在我正试图找出如何打印用户应该停留和切换的百分比。在

测试输入如下:

25
7
exit

程序应输出的内容如下:

^{pr2}$

以下是我的程序输出:

Enter Random Seed:
25
Welcome to Monty Hall Analysis
Enter 'exit' to quit
How many tests should we run?
7
Game 1
Doors: ['G', 'C', 'G']
Player Selects Door 1
Monty Selects Door 3
Player should switch to win.
Game 2
Doors: ['G', 'C', 'G']
Player Selects Door 2
Monty Selects Door 1
Player should stay to win.
Game 3
Doors: ['C', 'G', 'G']
Player Selects Door 1
Monty Selects Door 3
Player should stay to win.
Game 4
Doors: ['G', 'G', 'C']
Player Selects Door 3
Monty Selects Door 2
Player should stay to win.
Game 5
Doors: ['G', 'G', 'C']
Player Selects Door 3
Monty Selects Door 2
Player should stay to win.
Game 6
Doors: ['G', 'C', 'G']
Player Selects Door 3
Monty Selects Door 1
Player should switch to win.
Game 7
Doors: ['C', 'G', 'G']
Player Selects Door 2
Monty Selects Door 3
Player should switch to win.
How many tests should we run?

这是我做的代码:

import random
import sys

try:
    randSeed = int(input('Enter Random Seed:\n'))
    random.seed(randSeed)
except ValueError:
    sys.exit("Seed is not a number!")

print('Welcome to Monty Hall Analysis')
print("Enter 'exit' to quit")

while True:
    testNum = input('How many tests should we run?\n')
    valid = False
    while not valid:
        try:
            if testNum == "exit":
                sys.exit("Thank you for using this program.")
            else:
                testNum = int(testNum)
                valid = True
        except ValueError:
            testNum = input('Please enter a number:\n')
    pStay = 0
    pChange = 0
    numGame = 0
    for numGame in range(1, testNum + 1):
        doorList = ['C', 'G', 'G']
        random.shuffle(doorList)
        print('Game', numGame)
        print('Doors:', doorList)
        playerDoor = random.randint(0,2)
        montyDoor = random.randint(0,2)
        print('Player Selects Door', playerDoor+1)
        while montyDoor == playerDoor or doorList[montyDoor] == 'C':
            montyDoor = random.randint(0,2)
        print('Monty Selects Door', montyDoor+1)
        if doorList[playerDoor] == 'C':
            var = 0
        else:
            var = 1

        if var == 0:
            pStay += 1
            print('Player should stay to win.')
            pStay += 1
        if var == 1:
            print('Player should switch to win.')

抱歉,如果我的代码看起来不正确或令人困惑。这是我第一次编程谢谢。在


Tags: togameexitrandomwinselectsplayerprint
3条回答

下面是Python3.6对使用集合进行交易的通用版本的模拟。在makea Deal的广义版本中,门和要打开的门的数量是不同的。参考:

https://math.stackexchange.com/questions/608957/monty-hall-problem-extended

如果在doors=3和doors U to_open=1的情况下运行,如果不选择切换门,则预期结果为33%,而在切换门时,预期结果为66%。在

#!/usr/bin/env python
'''  application of Make a deal statistics
     application is using sets {}
     for reference see:
https://math.stackexchange.com/questions/608957/monty-hall-problem-extended
'''
import random


def Make_a_Deal(doors, doors_to_open):
    '''  Generalised function of Make_a_Deal. Logic should be self explanatory
         Returns win_1 for the option when no change is made in the choice of
         door and win_2 when the option to change is taken.
    '''
    win_1, win_2 = False, False

    doors = set(range(1, doors+1))
    price = set(random.sample(doors, 1))
    choice1 = set(random.sample(doors, 1))
    open = set(random.sample(doors.difference(price).
               difference(choice1), doors_to_open))
    choice2 = set(random.sample(doors.difference(open).
                  difference(choice1), 1))
    win_1 = choice1.issubset(price)
    win_2 = choice2.issubset(price)

    return win_1, win_2


def main():
    '''  input:
         - throws: number of times to Make_a_Deal (must be > 0)
         - doors: number of doors to choose from (must be > 2)
         - doors_to_open: number of doors to be opened before giving the 
           option to change the initial choice (must be > 0 and <= doors-2)
    '''

    try:
        throws = int(input('how many throws: '))
        doors = int(input('how many doors: '))
        doors_to_open = int(input('how many doors to open: '))
        if (throws < 1) or (doors < 3) or \
                (doors_to_open > doors-2) or (doors_to_open < 1):
            print('invalid input')
            return

    except Exception as e:
        print('invalid input: ', e)
        return

    number_of_wins_1, number_of_wins_2, counter = 0, 0, 0

    while counter < throws:
        win_1, win_2 = Make_a_Deal(doors, doors_to_open)

        if win_1:
            number_of_wins_1 += 1
        if win_2:
            number_of_wins_2 += 1

        counter += 1
        print('completion is {:.2f}%'.
              format(100*counter/throws), end='\r')

    print('number of wins option 1 is {:.2f}%: '.
          format(100*number_of_wins_1/counter))
    print('number of wins option 2 is {:.2f}%: '.
          format(100*number_of_wins_2/counter))


if __name__ == '__main__':
    main()

好吧,你要记录下球员应该留下来赢得比赛的次数。所以停留百分比就是“(pStay/float(testNum))*100”,然后简单地从100中减去这个数字,得到要更改的百分比(因为它们必须加起来达到100%)

我想我应该提供更多的信息。这个公式是把停留游戏的数量从游戏总数中去掉。乘以100可以将十进制值转换为百分比。在

所以,如果你在1场比赛中,你打了10场比赛,那就是1/10,也就是0.1乘以100,就是10%。在

既然1/10你应该留下来,那就意味着9/10你应该改变。所以你可以减去停留百分比得到变化百分比,即100%-10%=90%

我把float()转换放在代码中的原因是,在python2中,如果将整数除以整数,它不会计算小数部分。它只是向下舍入到整数值。所以1/10等于0,不是1。在python3中,它确实产生了一个分数值,但是由于我不知道您使用的是哪个版本,所以可以安全地将其转换为float以获得预期的结果

看到下面添加的评论,你很接近。但是您缺少pSwitch的sum count变量。希望这有帮助。在

import random
import sys

try:
    randSeed = int(input('Enter Random Seed:\n'))
    random.seed(randSeed)
except ValueError:
    sys.exit("Seed is not a number!")

print('Welcome to Monty Hall Analysis')
print("Enter 'exit' to quit")

while True:

    # Total Number of Games
    testNum = input('How many tests should we run?\n')

    valid = False
    while not valid:
        try:
            if testNum == "exit":
                sys.exit("Thank you for using this program.")
            else:
                testNum = int(testNum)
                valid = True
        except ValueError:
            testNum = input('Please enter a number:\n')
    pStay = 0
    pSwitch = 0  # Also need a running count var for switch
    numGame = 0
    for numGame in range(1, testNum + 1):
        doorList = ['C', 'G', 'G']
        random.shuffle(doorList)
        print('Game', numGame)
        print('Doors:', doorList)
        playerDoor = random.randint(0,2)
        montyDoor = random.randint(0,2)
        print('Player Selects Door', playerDoor+1)
        while montyDoor == playerDoor or doorList[montyDoor] == 'C':
            montyDoor = random.randint(0,2)
        print('Monty Selects Door', montyDoor+1)
        if doorList[playerDoor] == 'C':
            var = 0
        else:
            var = 1

        if var == 0:
            #pStay+=1  - - Not sure why you have two increments for pStay.. only need one.
            print('Player should stay to win.')
            pStay += 1
        if var == 1:
            print('Player should switch to win.')
            pSwitch += 1 # Also increment the pSwitch

    # Print out the percentages
    print('\n')    
    print("Percentage of times player should have STAYED: ",(pStay/testNum) * 100, "%")
    print("Percentage of times player should have SWITCHED: ",(pSwitch/testNum) * 100, "%")

相关问题 更多 >

    热门问题