标签:def wrap game 小数 text 模拟 mat 表示 sim
import random
from math import *
def printIntro():#打印程序的介绍性信息
print("模拟乒乓球竞赛")
print("学号23")
print("程序运行需要A和B的能力值(以0到1之间的小数表示)")
def getInputs():#获得用户输入的参数
a = eval(input("请输入选手A的能力值(0-1): "))
b = eval(input("请输入选手B的能力值(0-1): "))
h= eval(input("请输入一场要打几局:"))
n = eval(input("模拟比赛的场次: "))
return a, b, h,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 gameOver(scoreA, scoreB):
g=scoreA-scoreB
if (abs(g)==2 and scoreA> 10 and scoreB> 10) or (g> 0 and scoreA==11) or (g<0 and scoreB==11):
return scoreA,scoreB
def simOneGame(probA, probB,h):#模拟一场比赛
for i in range(h): #模拟七局四胜或五局三胜为一场
serving = "A"
roundA =roundB=0 #分别为队伍A和B的赢得的比赛的局次
scoreA, scoreB = 0, 0
while not gameOver(scoreA, scoreB): #模拟一局比赛
roundA=roundB=0
if serving == "A":
if random.random() < probA:
scoreA += 1
else:
serving = "B"
else:
if random.random() < probB:
scoreB += 1
else:
serving = "A"
if scoreA>scoreB:
roundA += 1
else:
roundB += 1
return roundA,roundB
def simNGames(n ,probA, probB,h):#利用A,B的的能力值模拟N场比赛
winsA, winsB = 0, 0
for i in range(n):
roundA , roundB = simOneGame(probA, probB,h)
if roundA >roundB:
winsA += 1
else:
winsB += 1
return winsA, winsB
def main():
printIntro()
probA, probB, h,n = getInputs()#分别为队伍A和B的能力值,一场的局数,比赛的场次
winsA, winsB = simNGames(n, probA, probB,h)#分别为队伍A和B的赢得的比赛的场次
printSummary(winsA, winsB)
if h==7:
print(‘此次模拟单打淘汰赛‘)
else:
print(‘此次模拟双打淘汰赛或者是团体淘汰赛‘)
main()
标签:def wrap game 小数 text 模拟 mat 表示 sim
原文地址:https://www.cnblogs.com/gtxy/p/12883119.html