diceGame.py(下面)中的python代码包含我们在课堂上讨论过的骰子游戏的python实现。假设我们运行代码N次并根据A出现的次数除以N来估计某个事件A,P r {A}的概率。然后我们重复这个过程M次收集概率pi,i = 1 ,。 。 。 ,M。假设两个骰子都是公平的,使用N = 10,100,1000和M = 100修改diceGame.py的主程序,以获得以下概率:
在第一个骰子上赢得比赛的概率。
如果第一次掷骰得分为4,则赢得比赛的概率。
赢得比赛的概率。
游戏需要超过5个骰子的概率。
我知道所有这些答案都可以通过代码本身轻松提供。我的问题是我不知道如何编辑python代码来提供这些所需的输出。
以下是代码:
# ===============================
# IMPORTS RANDOM NUMBER GENERATOR
# ===============================
import random
# ================================================================
# GENERATES RANDOMLY THE SUM OF TWO INTEGERS IN THE [1,6] INTERVAL
# ================================================================
def rollDices():
return int(random.randint(1,6) + random.randint(1,6))
# ================================================
# RETURN THE OUTCOME STRING GIVEN AN INTEGER STATE
# ================================================
def getOutcome(outcome):
if(outcome == 0):
result = "Lost at first roll."
elif(outcome == 1):
result = "Won at first roll."
elif(outcome == 2):
result = "Won on [4,5,6,8,9,10]"
elif(outcome == 3):
result = "Lost on [4,5,6,8,9,10]"
return result
# ==============
# PLAYS THE GAME
# ==============
def playGame():
# Define Variables
gameFinished = False
wonGame = False
totRolls = 0
while (not(gameFinished)):
# ROLL DICES
totScore = rollDices()
totRolls += 1;
# GAME IS LOST
if(totScore in [2,3,12]):
gameFinished = True
wonGame = False
return 0,wonGame,totRolls,totScore
# GAME IS WON
if(totScore in [7,11]):
gameFinished = True
wonGame = True
return 1,wonGame,totRolls,totScore
# JUST CONTINUE PLAYING
if(totScore in [4,5,6,8,9,10]):
# REPEAT UNTIL YOU FIND THE SCORE AGAIN OR 7
newScore = 0
while((newScore != totScore)and(newScore != 7)):
newScore = rollDices()
totRolls += 1;
# CHECK IF YOU WIN OR LOOSE
if(newScore == totScore):
gameFinished = True
wonGame = True
return 2,wonGame,totRolls,totScore
if(newScore == 7):
gameFinished = True
wonGame = False
return 3,wonGame,totRolls,totScore
# ============
# MAIN PROGRAM
# ============
if __name__ == "__main__":
intVal,wonGame,numRolls,lastScore = playGame()
print("Outcome: %s" % (getOutcome(intVal)))
if(wonGame):
print("You have won the game.")
else:
print("You have lost the game.")
print("Total rolls needed for this game: %d" % (numRolls))
print("Last outcome: %d" % (lastScore))
我尝试解决问题时的新主要功能:
if __name__ == "__main__":
m = 100
n = 10
FRwins = 0
for i in range(m):
for j in range(n):
intVal,wonGame,numRolls,lastScore = playGame()
if getOutcome(intVal) == 1:
FRwins += 1
FRwins = FRwins/float(n)
print(FRwins)
答案 0 :(得分:1)
目前这个节目正在玩游戏一次。如果你查看最后10行代码,那就是你想要调整的代码。重要的是这个:
intVal,wonGame,numRolls,lastScore = playGame()
它只被调用一次,所以你只能得到一个结果。由于您需要进行蒙特卡罗模拟(即反复播放和跟踪概率),您只需要多次重播此行,并每次跟踪结果。
从那里,您需要设置一些for循环,例如:
for i in range(m):
并跟踪每次模拟的结果。由于你正在使用m和n,你需要围绕你的playGame()的嵌套循环。然后你只需要计算结果,然后除以获得概率的总尝试次数。
希望这很有帮助。随意提出进一步的问题 - 我试图保持足够的一般性,以至于我实际上并没有为你的家庭作业编写代码!