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 printSummary(n,winsA, winsB):
M=winsA+winsB
print(“竞技分析开始, 共模拟{}场比赛”.format(n))
print(“选手A获胜{}次比赛, 占比{:0.1%}”.format(winsA, winsA/M))
print(“选手B获胜{}次比赛, 占比{:0.1%}”.format(winsB, winsB/M))
def simOneGame(probA, probB):
scoreA, scoreB = 0, 0
serving = “A”
while True:
if serving == “A”:
if random.random() < probA:
scoreA += 1
else:
serving = “B”
elif serving == “B”:
if random.random() < probB:
scoreB += 1
else:
serving = “A”
if scoreA==29 and scoreB==29:
if random.random() < probA:
scoreA += 1
else:
scoreB+=1
break
elif (scoreA==21 and scoreB<20) or (scoreB==21 and scoreA<20):
break
elif scoreA>=20 and scoreB>=20:
if random.random() < probA:
scoreA += 1
else:
scoreB+=1
if abs(scoreA-scoreB)==2:
break
return scoreA, scoreB
def simNGames(n ,probA, probB):
winsA,winsB = 0, 0
suma, sumb = 0, 0
for i in range(n):
scoreA, scoreB = simOneGame(probA, probB)
if scoreA > scoreB:
suma+= 1
else:
sumb+= 1
if suma==2:
winsA+=1
suma=0
sumb=0
elif sumb==2:
winsB+=1
suma=0
sumb=0
return winsA,winsB
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(n,winsA, winsB)
main()

 

版权声明:本文为w2538060594原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/w2538060594/p/12750887.html