其他分享
首页 > 其他分享> > 比赛

比赛

作者:互联网

 1# -*- coding: utf-8 -*-
 2 from random import random
 3 def printIntro():
 4     print("这个程序模拟两个选手A和B的兵乓球比赛")
 5     print("程序运行需要A和B选手的能力值(以0到1之间的小数表示)")
 6 def getInput():
 7     probA=eval(input("请输入选手A的能力值(0-1):"))
 8     probB=eval(input("请输入选手B的能力值(0-1):"))
 9     n=eval(input("模拟比赛场次:"))
10     return probA,probB,n
11 def simGames(n,probA,probB):     #比赛双方各自胜利的场次数
12     winsA,winsB=0,0
13     for i in range (n):
14         c=simGame(probA,probB)
15         if c=='A':
16             winsA+=1
17         else:
18             winsB+=1
19     return winsA,winsB
20 def simGame(probA,probB):         #判断一场比赛的胜方
21     winsA1,winsB1=0,0
22     for i in range(7):
23         scoreA,scoreB=simoneGame(probA,probB)
24         if scoreA>scoreB:
25             winsA1+=1
26         else:
27             winsB1+=1      
28     if winsA1>=4:
29         return 'A'
30     return 'B'
31 def simoneGame(probA,probB):     #统计一场比赛下来的各自得分数
32     scoreA,scoreB=0,0
33     serving="A"
34     while not gameOver(scoreA,scoreB):
35         x=random()
36         if serving=="A":
37             if x < probA:
38                 scoreA+=1
39             else:
40                 serving="B"
41         else:
42             if x < probB:
43                 scoreB+=1
44             else:
45                 serving="A"
46     return scoreA,scoreB
47 def gameOver(a,b):            
48     if (a>=11 and b<11) or (b>=11 and a<11) or (a>9 and b>9 and ((a-b)>=2 or (b-a)>=2)):
49         return True
50     return False
51 def printsummary(winsA,winsB):
52     n=winsA+winsB
53     print("竞技开始分析,共模拟了{}场比赛".format(n))
54     print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA,winsA/n))
55     print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB,winsB/n))
56     print("分析人:Yong No.10")
57 def main():
58     printIntro()
59     probA,probB,n=getInput()
60     winsA,winsB=simGames(n,probA,probB)
61     printsummary(winsA,winsB)
62 main()    

标签:winsB,winsA,return,比赛,probB,probA,def
来源: https://www.cnblogs.com/M-Inori/p/15551169.html