模拟两位选手进行n羽毛球比赛(15分赛制)并计算模拟胜率

 1 #羽毛球比赛预测
 2 from random import random
 3 def printTips():
 4     print("这个程序模拟两个选手A和B进行羽毛球比赛")
 5     print("程序运行需要A和B的能力值(以0到1之间的小数表示)")
 6 def getInputs():
 7     a = eval(input("请输入选手A的能力值(0-1): "))
 8     b = eval(input("请输入选手B的能力值(0-1): "))
 9     n = eval(input("模拟羽毛球比赛的场次: "))
10     return a, b, n
11 def ModelNGames(n, powerA, powerB):
12     winsA, winsB = 0, 0
13     for i in range(n):
14         scoreA, scoreB = ModelOneGame(powerA, powerB)
15         if scoreA > scoreB:
16             winsA += 1
17         else:
18             winsB += 1
19     return winsA, winsB
20 def gameOver(a,b):
21     return a==15 or b==15
22 def ModelOneGame(powerA, powerB):
23     scoreA, scoreB = 0, 0
24     serving = "A"
25     while not gameOver(scoreA, scoreB):
26         if serving == "A":
27             if random() < powerA:
28                 scoreA += 1
29             else:
30                 serving="B"
31         else:
32             if random() < powerB:
33                 scoreB += 1
34             else:
35                 serving="A"
36     return scoreA, scoreB
37 def printResult(winsA, winsB):
38     n = winsA + winsB
39     print("共模拟了{}场羽毛球比赛".format(n))
40     print("选手A获胜{}场比赛,模拟赛胜率{:0.1%}".format(winsA, winsA/n))
41     print("选手B获胜{}场比赛,模拟赛胜率{:0.1%}".format(winsB, winsB/n))
42 def main():
43     printTips()
44     powerA, powerB, n = getInputs()
45     winsA, winsB = ModelNGames(n, powerA, powerB)
46     printResult(winsA, winsB)
47 main()

 

posted @ 2020-04-21 08:39  贾诩来编程  阅读(364)  评论(0编辑  收藏  举报