簡體   English   中英

讓我們做個交易python游戲

[英]Let's make a deal python game

我需要編寫一個基於舊電視節目的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 可將十進制值轉換為百分比。

因此,如果您應該留在 1 場比賽中,並且您打了 10 場比賽,那將是 1/10,即 0.1,乘以 100,是 10%。

因為 1/10 你應該留下,這意味着 9/10 你應該改變。 所以你可以減去停留百分比得到變化百分比,即100% - 10% = 90%

我將 float() 轉換放在代碼中的原因是因為在 python2 中,如果將整數除以整數,它不會計算小數部分。 它只是向下舍入到整數值。 所以 1/10 會給你 0,而不是 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, "%")

這是使用集合的 Make a Deal 通用版本的 Python 3.6 模擬。 在 Make a Deal 的通用版本中,門的數量和要打開的門的數量是可變的。 見參考:

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

如果在doors = 3 和doors_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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM