错误 的模拟循环比赛
作者:互联网
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(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 gameOver1(a, b):
if a>=15 and a>b:
return (a-b)==2
if b>=15 and b>a:
return (b-a)==2
else:
return False
def gameOver2(a,b):
if a>=25 and a>b:
return (a-b)==2
elif b>=25 and b>a:
return (b-a)==2
else:
return False
def simOneGame(probA, probB):
scoreA, scoreB = 0, 0
for i in range(4):
cA,cB=0,0
serving = "A"
while not gameOver2(cA,cB):
if serving == "A":
if random.random() < probA:
cA+=1
else:
cB+=1
serving = "B"
else:
if random.random() < probB:
cB += 1
else:
cA+=1
serving = "A"
if cA>cB:
scoreA +=1
else:
scoreB +=1
if scoreA==scoreB:
cA,cB=0,0
serving = "A"
while not gameOver1(cA,cB):
if serving == "A":
if random.random() < probA:
cA += 1
if cA==8 and cA>cB:
serving ='B'
else:
serving = "B"
else:
if random.random() < probB:
cB += 1
if cB==8 and cB>cA:
serving ='A'
else:
serving = "A"
if cA>cB:
scoreA +=1
else:
scoreB +=1
return scoreA,scoreB
def simNGames(n ,probA, probB):
winsA, winsB = 0, 0
for i in range(n):
scoreA, scoreB = simOneGame(probA, probB)
if scoreA > scoreB:
winsA += 1
else:
winsB += 1
return winsA, winsB
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)
main()
显示错误
标签:winsB,serving,比赛,cB,cA,else,循环,winsA,模拟 来源: https://www.cnblogs.com/----zcy88888/p/15551281.html