标签:over 次数 int fabs man get one mes sum
观众朋友们,大家好,您现在收看的是2019年全球乒乓球总决赛,下面有请双方选手上场
def printIntroduce(): print(‘This program simulates a game between two players,A and B‘) print(‘Probability (a number between 0 and 1) is used!‘)
经过我们权威专家对两位选手之前比赛表现,估算出两位选手的大概实力
def getInputs(): a=eval(input(‘What is the probability of player A wins?‘)) b=eval(input(‘What is the probability of player B wins?‘)) n=eval(input(‘How many games to simulate?‘)) return a,b,n
比赛规则采用七局四胜制,每局比赛先得11分或10平后先得2分的选手为胜
def simulateNGames(n,probabilityA,probabilityB):#定义球员A,B赢得比赛的次数,初始值为0 winsA=0 winsB=0#通过for循环来模拟n场比赛 for i in range(n):#simulateOneGame()用来模拟一场比赛#输入为球员的能力值,即每场比赛中每一回合获胜的可能性#返回的是本场比赛2个球员的得分#根据返回的得分来确定本场比赛的胜负 scoreA,scoreB=simulateOneGame(probabilityA,probabilityB) if scoreA>scoreB: winsA+=1 else: winsB+=1 return winsA,winsB
def simulateOneGame(probabilityA,probabilityB):#每场比赛,2个球员的得分初始为 scoreA=0 scoreB=0 f=0 n=probabilityA+probabilityB A=probabilityA/n B=probabilityB/n while not((gameover1(scoreA,scoreB) and f==0)or(gameover2(scoreA,scoreB) and f==1)): if random()<A: scoreA+=1 else: scoreB+=1 if scoreA==scoreB==10: f=1 return scoreA,scoreB def gameover1(a,b): return a==11 or b==11 def gameover2(a,b): return math.fabs(a-b)==2
废话不多说,赶紧比赛吧
from random import * import math def main(): printIntroduce()#打印程序的介绍信息 probabilityA,probabilityB,n=getInputs()#通过simulateNGames()求得2个球员在n次比赛中获胜的次数 winsA,winsB=simulateNGames(n,probabilityA,probabilityB)#通过printSummary()来输出比赛的结果信息 printSummary(winsA,winsB)
......
接下来公布比赛成绩
def printSummary(winsA,winsB): n=winsA+winsB print(‘\nGames simulated:%d‘ % n) print(‘Wins for A:{0}({1:.1%})‘.format(winsA,winsA/n)) print(‘Wins for B:{0}({1:0.1%})‘.format(winsB,winsB/n))
标签:over 次数 int fabs man get one mes sum
原文地址:https://www.cnblogs.com/guyuanlin/p/10849859.html