预计球赛比赛成绩
(一)模拟体育竞技分析
b.排球比赛
from random import random 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 simNGames(n, probA, probB): winsA, winsB = 0, 0 for i in range(n): scoreA, scoreB=simOneGame(probA, probB) if scoreA==1: winsB+=1 continue elif scoreA==3: winsA+=1 continue scoreA, scoreB = simOneGame5(probA, probB) if scoreA > scoreB: winsA += 1 else: winsB += 1 return winsA, winsB def simOneGame5(probA, probB): scoreA, scoreB =0, 0 serving = 'A' while not gameOver5(scoreA, scoreB): if serving == 'A': if random() > probA: scoreB += 1 serving = 'B' else: scoreA += 1 else: if random() > probB: scoreA += 1 serving = 'A' else: scoreB += 1 return scoreA, scoreB def simOneGame(probA, probB): scoreA, scoreB = 0, 0 for i in range(4): s1, s2=0, 0 while not gameOver(s1, s2): if random()<probA: s1+=1 elif random()<probB: s2+=1 if s1>s2: scoreA+=1 else: scoreB+=1 return scoreA, scoreB def gameOver5(c, d): return (c>=15 and c-d>=2) or (d>=15 and d-c>=2) def gameOver(scoreA, scoreB): return (scoreA>=25 and scoreA-scoreB>=2) or (scoreB>=25 and scoreB-scoreA>=2) def printSummary(n,winsA, winsB): print("竞技分析开始,共模拟{}场比赛".format(n)) print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA, winsA/n)) print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB, winsB/n)) def main(): printIntro() probA, probB,n= getInputs() winsA, winsB = simNGames(n, probA, probB) printSummary(n,winsA, winsB) main()