【作业】模拟体育竞技分析

 1 from random import *
 2 import sys
 3 def main():
 4     printIntroduce()
 5     probabilityA,probabilityB,n=getInputs()
 6     
 7     winsA,winsB=simulateNGames(n,probabilityA,probabilityB)
 8     
 9     printSummary(winsA,winsB)
10 
11 
12 def printIntroduce():
13     print('乒乓球比赛模拟器,学号03')
14 
15 
16 def getInputs():
17     a=eval(input('选手A的获胜概率?(小数):'))
18     b=eval(input('选手B的获胜概率?(小数):'))
19     n=eval(input('比赛5场还是7场?:'))
20     if(n!=5 and n!=7):
21         print("场数不符合规则。")
22         sys.exit()
23     return a,b,n
24 
25 def simulateNGames(n,probabilityA,probabilityB):
26     
27     winsA=0
28     winsB=0
29     
30     for i in range(n):
31         
32         scoreA,scoreB=simulateOneGame(probabilityA,probabilityB)
33         if scoreA>scoreB:
34             winsA+=1
35         else:
36             winsB=winsB+1
37         if winsA>n/2 or winsB>n/2:
38             return winsA,winsB
39     return winsA,winsB
40 
41 def printSummary(winsA,winsB):
42     n=winsA+winsB
43     print('\n模拟比赛场数:%d' % n)
44     print('A选手赢:{0}({1:.1%})'.format(winsA,winsA/n))
45     print('B选手赢:{0}({1:0.1%})'.format(winsB,winsB/n))
46 
47 
48 
49 def simulateOneGame(probabilityA,probabilityB):
50     
51     scoreA=0
52     scoreB=0
53     
54     starting='A'
55     while not gameOver(scoreA,scoreB):
56         if starting=='A':
57             
58             if random()<probabilityA:
59                 scoreA+=1
60             else:
61                 starting='B'
62         else:
63             if random()<probabilityB:
64                 scoreB=scoreB+1
65             else:
66                 starting='A'
67     return scoreA,scoreB
68 
69 
70 def gameOver(a,b):
71     return (a>=11 and a-b>=2) or (b>=11 and b-1>=2)
72 
73 
74 if __name__=='__main__':
75     main()

 

posted @ 2020-11-22 22:55  littlechang  阅读(88)  评论(0)    收藏  举报