1 import random
2 from math import *
3 def printIntro():#打印程序的介绍性信息
4 print("模拟乒乓球竞赛")
5 print("学号12")
6 print("程序运行需要A和B的能力值(以0到1之间的小数表示)")
7
8
9 def getInputs():#获得用户输入的参数
10 a = eval(input("请输入选手A的能力值(0-1): "))
11 b = eval(input("请输入选手B的能力值(0-1): "))
12 h= eval(input("请输入一场要打几局:"))
13 n = eval(input("模拟比赛的场次: "))
14 return a, b, h,n
15
16 def printSummary(winsA, winsB):
17 n = winsA + winsB
18 print("竞技分析开始, 共模拟{}场比赛".format(n))
19 print("选手A获胜{}场比赛, 占比{:0.1%}".format(winsA, winsA/n))
20 print("选手B获胜{}场比赛, 占比{:0.1%}".format(winsB, winsB/n))
21 def gameOver(scoreA, scoreB):
22 g=scoreA-scoreB
23 if (abs(g)==2 and scoreA> 10 and scoreB> 10) or (g> 0 and scoreA==11) or (g<0 and scoreB==11):
24 return scoreA,scoreB
25
26
27 def simOneGame(probA, probB,h):#模拟一场比赛
28 for i in range(h): #模拟七局四胜或五局三胜为一场
29 serving = "A"
30 roundA =roundB=0 #分别为队伍A和B的赢得的比赛的局次
31 scoreA, scoreB = 0, 0
32 while not gameOver(scoreA, scoreB): #模拟一局比赛
33 roundA=roundB=0
34 if serving == "A":
35 if random.random() < probA:
36 scoreA += 1
37 else:
38 serving = "B"
39 else:
40 if random.random() < probB:
41 scoreB += 1
42
43 else:
44 serving = "A"
45 if scoreA>scoreB:
46 roundA += 1
47 else:
48 roundB += 1
49 return roundA,roundB
50
51
52 def simNGames(n ,probA, probB,h):#利用A,B的的能力值模拟N场比赛
53 winsA, winsB = 0, 0
54 for i in range(n):
55 roundA , roundB = simOneGame(probA, probB,h)
56 if roundA >roundB:
57 winsA += 1
58 else:
59 winsB += 1
60 return winsA, winsB
61
62 def main():
63 printIntro()
64 probA, probB, h,n = getInputs()#分别为队伍A和B的能力值,一场的局数,比赛的场次
65 winsA, winsB = simNGames(n, probA, probB,h)#分别为队伍A和B的赢得的比赛的场次
66 printSummary(winsA, winsB)
67 if h==7:
68 print('此次模拟单打淘汰赛')
69 else:
70 print('此次模拟双打淘汰赛或者是团体淘汰赛')
71 main()
![]()