#!/usr/bin/env python3 # -*- coding: utf-8 -*- #matchSim.py from random import * def main(): printIntro() probA,probB,n = getInputs() winsA, winsB = simNGames(n,probA,probB) PrintSummary(winsA, winsB) def printIntro(): print('本程序可模拟两个运动员之间的比赛结果') print('假设有两个运动员甲和乙') print('以往获胜概率如下:(0到1之间的数字)') def getInputs(): a = eval(input('运动员甲获胜的概率是?')) b = eval(input('运动员乙获胜的概率是?')) n = eval(input('模拟他们之间比赛的场次?')) return a,b,n def simNGames(n,probA,probB): winsA = 0 winsB = 0 for i in range(n): scoreA,scoreB = simOneGame(probA,probB) if scoreA >scoreB: winsA = winsA + 1 else: winsB = winsB + 1 return winsA,winsB def simOneGame(probA,probB): #一场比赛的结果预测 ''' 假设发球权在甲手时,获得的随机数小于甲的获胜概率,则甲得分加一分,甲继续发球, 如果获得的随机数大于甲时,甲不得分,甲把发球权交换给乙; 假设乙获得发球权后,获得的随机数小于乙的获胜概率,则乙得分加一分,乙继续发球, 如果获得的随机数大于乙时,乙不得分,乙把发球权交换给甲。 然后返回甲乙的分数 ''' scoreA = 0 scoreB = 0 serving = "甲" while not gameOver(scoreA,scoreB): #哪个先到15分一场比赛结束 if serving == "甲": if random() < probA: #random()函数每次获取0到1之间的随机数 scoreA = scoreA + 1 else: serving = "乙" else: if random() < probB: scoreB = scoreB + 1 else: serving = "甲" return scoreA,scoreB def gameOver(a,b): return a==15 or b==15 def PrintSummary(winsA, winsB): n = winsA + winsB print(' 比赛模拟:%d'%n) print('甲获胜场次:{0}({1:0.1%})'.format(winsA,winsA/n)) print('乙获胜场次:{0}({1:0.1%})'.format(winsB,winsB/n)) if __name__ == '__main__': main()