【发布时间】:2018-07-30 08:38:07
【问题描述】:
diceGame.py(如下)中的 Python 代码包含我们在课堂上讨论的骰子游戏的 Python 实现。假设我们运行代码 N 次并根据 A 发生的次数除以 N 来估计某个事件 A 的概率 P r{A}。然后我们重复这个过程 M 次收集概率 pi, i = 1 , . . . , M. 假设两个骰子都是公平的,修改 diceGame.py 的主程序,使用 N = 10, 100, 1000 和 M = 100 获得以下概率:
第一次掷骰子时获胜的概率。
如果第一次掷出 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)
【问题讨论】:
-
@Evert 我已经做出了您推荐的更改。
标签: python python-3.x random dice