目錄python
體育競技分析框架
高手過招,勝負只在毫釐之間dom
解決複雜問題的有效方法模塊化
逐步組建複雜系統的有效測試方法單元測試
程序整體框架及步驟測試
步驟4:輸出球員A和B獲勝比賽的場次及機率設計
printSummary()3d
def main(): printIntro() probA, probB, n = getInputs() winsA, winsB = simNGames(n, probA, probB) printSummary(winsA, winsB) def printIntro(): """介紹性內容,提升用戶體驗""" print("這個程序模擬兩個選手A和B的某種競技比賽") print("程序運行須要A和B的能力值(以0到1之間的小數表示)") def getInputs(): a = eval(input("請輸入選手A的能力值(0-1): ")) b = eval(input("請輸入選手B的能力值(0-1): ")) n = eval(input("模擬比賽的場次: ")) return a, b, n def printSummary(winsA, winsB): n = winsA + winsB print("競技分析開始,共模擬{}場比賽".format(n)) print("選手A獲勝{}場比賽,佔比{:0.1%}".format(winsA, winsA/n)) print("選手B獲勝{}場比賽,佔比{:0.1%}".format(winsB, winsB/n))
def simNGames(n, probA, probB): winsA, winsB = 0, 0 for i in range(n): scoreA, scoreB = simOneGame(probA, probB) if scoreA > scoreB: winsA += 1 else: winsB += 1 return winsA, winsB
根據分數判斷局的結束code
def simOneGame(probA, probB): scoreA, scoreB = 0, 0 serving = "A" while not gameOver(scoreA, scoreB): if serving == "A": if random() < probA: scoreA += 1 else: serving = "B" else: if random() < probB: scoreB += 1 else: serving = "A" return scoreA, scoreB def gameOver(a,b): return a==15 or b==15