Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 让';让我们来做个交易吧_Python_Logic - Fatal编程技术网

Python 让';让我们来做个交易吧

Python 让';让我们来做个交易吧,python,logic,Python,Logic,我被要求编写一个基于老电视节目《让我们达成协议》的python程序。我让程序打印出游戏的数量以及用户是否应该切换或留下。现在,我正试图找出如何打印用户应该留下并完全切换的时间百分比 以下是测试输入的内容: 25 7 exit 以下是程序应输出的内容: Game 1 Doors : [ ’G’, ’C’, ’G’ ] Player Selects Door 1 Monty Selects Door 3 Player should switch to win. Game 2 Doors : [ ’

我被要求编写一个基于老电视节目《让我们达成协议》的python程序。我让程序打印出游戏的数量以及用户是否应该切换或留下。现在,我正试图找出如何打印用户应该留下并完全切换的时间百分比

以下是测试输入的内容:

25
7
exit
以下是程序应输出的内容:

Game 1
Doors : [ ’G’, ’C’, ’G’ ]
Player Selects Door 1
Monty Selects Door 3
Player should switch to win.
Game 2
Doors : [ ’C’, ’G’, ’G’ ]
Player Selects Door 2
Monty Selects Door 3
Player should switch to win.
Game 3
Doors : [ ’G’, ’C’, ’G’ ]
Player Selects Door 1
Monty Selects Door 3
Player should switch to win.
Game 4
Doors : [ ’C’, ’G’, ’G’ ]
Player Selects Door 2
Monty Selects Door 3
Player should switch to win.
Game 5
Doors : [ ’G’, ’G’, ’C’ ]
Player Selects Door 3
Monty Selects Door 1
Player should stay to win.
Game 6
Doors : [ ’G’, ’C’, ’G’ ]
Player Selects Door 2
Monty Selects Door 1
Player should stay to win.
Game 7
Doors : [ ’G’, ’G’, ’C’ ]
Player Selects Door 2
Monty Selects Door 1
Player should switch to win.
Stay Won 28.6% of the time.
Switch Won 71.4% of the time.
How many tests should we run?
Thank you for using this program.
以下是我的程序输出:

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.')

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

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

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

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

因为1/10你应该留下来,这意味着9/10你应该改变。因此,您可以减去停留百分比以获得更改百分比,即100%-10%=90%


我之所以在代码中使用float()转换,是因为在python2中,如果将整数除以整数,它不会计算小数部分。它只是四舍五入到整数值。所以1/10会给你0,而不是1。在python3中,它确实会产生一个分数值,但由于我不知道您使用的是哪个版本,所以可以将其转换为浮点值以获得预期结果

请参见下面添加的注释,您已经接近了。但是,您缺少pSwitch的总和计数变量。希望这有帮助

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, "%")

下面是Python3.6对使用集合进行交易的通用版本的模拟。在“达成交易”的广义版本中,门的数量和打开的门的数量可以不同。请参阅以供参考:

如果在doors=3和doors_to_open=1的情况下运行,如果不选择切换doors,则预期结果为33%,如果选择切换doors,则预期结果为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()
#/usr/bin/env python
''交易统计数据的应用
应用程序正在使用集合{}
有关参考资料,请参阅:
https://math.stackexchange.com/questions/608957/monty-hall-problem-extended
'''
随机输入
def达成交易(门、门至门打开):
“达成交易”的广义功能。逻辑应该是不言自明的
当选项的选择没有更改时,返回选项的win_1
选择更改时,door和win_2。
'''
赢1,赢2=假,假
门=设置(范围(1,门+1))
价格=套(随机样本(门,1))
choice1=集合(随机样本(门,1))
打开=设置(随机。样品(门)。差异(价格)。
差异(选择1),门(打开)
choice2=设置(随机。样本(门)。差异(打开)。
差异(选项1,1))
win_1=选择1.发行集(价格)
win_2=选择2.发行集(价格)
返回win_1,win_2
def main():
''输入:
-抛出次数:达成交易的次数(必须大于0)
-门:可选择的门数(必须大于2)
-doors_to_open:在发出警告之前要打开的门的数量

用于更改初始选择的选项(必须大于0,并在代码上添加一些样式注释。不要使用变量名“var”。它根本不是描述性的。例如,使用“correctDoor”。此外,不要将其设置为1或0并进行比较。只需使用True和False。那么底部的代码可能是“if correctDoor”,您可以替换“if var==1”只使用一个“else”条件,因为不需要再次检查Hanks!您解释它的方式是有道理的。但是,我将把它放在代码中的什么位置?在我的最后一个if语句之后?请注意我在回答中所说的(pStay/testNum)只能在python3中正常工作。在python2中,它将执行整数除法,因此答案将始终舍入为0,不包括pstay==testNum的情况,其中它将为1。根据print语句的格式,我假设它是python3,但为了可移植性,我仍然建议使用cast to float()