from random import random print("学号尾数07") 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("模拟比赛的场次: ")) m = eval(input("模拟次数:")) return a, b, n, m def simNGames(n, probA, probB): winsA, winsB = 0, 0 scoreA_ls=[] scoreB_ls=[] for i in range(n): scoreA, scoreB = simOneGame(probA, probB) scoreA_ls.append(scoreA) scoreB_ls.append(scoreB) if scoreA > scoreB: winsA += 1 else: winsB += 1 return winsA, winsB,scoreA_ls,scoreB_ls def gameOver(a,b): if(a>=20 or b>=20): if(abs(a-b)==2 and a<=29 and b<=29): return True else: return a==30 or b==30 else: return False def simOneGame(probA, probB): scoreA, scoreB = 0, 0 serving = "A" while not gameOver(scoreA, scoreB): if serving == "A": if random() < probA: scoreA += 1 else: serving="B" else: if random() < probB: scoreB += 1 else: serving="A" return scoreA, scoreB def printSummary(winsA, winsB,m,scoreA_ls,scoreB_ls): n = winsA + winsB print("模型模拟次数{}".format(m)) print("竞技分析开始,共模拟{}场比赛".format(n)) print("A选手各场次得分比分:") print(scoreA_ls) print("B选手各场次得分比分:") print(scoreB_ls) print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA, winsA/n)) print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB, winsB/n)) def main(): printIntro() probA, probB, n, m= getInputs() for i in range(m): winsA, winsB,scoreA_ls,scoreB_ls = simNGames(n, probA, probB) printSummary(winsA, winsB,m,scoreA_ls,scoreB_ls)
运行结果如下:
学号尾数07
这个程序模拟两个选手A和B的羽毛球竞技比赛
程序运行需要A和B的能力值(以0到1之间的小数表示)
请输入选手A的能力值(0-1): 0.4
请输入选手B的能力值(0-1): 0.3
模拟比赛的场次: 6
模拟次数:8
模型模拟次数8
竞技分析开始,共模拟6场比赛
A选手各场次得分比分:
[30, 20, 30, 30, 30, 30]
B选手各场次得分比分:
[15, 18, 11, 11, 7, 18]
选手A获胜6场比赛,占比100.0%
选手B获胜0场比赛,占比0.0%
模型模拟次数8
竞技分析开始,共模拟6场比赛
A选手各场次得分比分:
[21, 30, 30, 30, 21, 30]
B选手各场次得分比分:
[19, 23, 19, 13, 23, 12]
选手A获胜5场比赛,占比83.3%
选手B获胜1场比赛,占比16.7%
模型模拟次数8
竞技分析开始,共模拟6场比赛
A选手各场次得分比分:
[18, 30, 30, 30, 30, 22]
B选手各场次得分比分:
[20, 20, 15, 18, 14, 20]
选手A获胜5场比赛,占比83.3%
选手B获胜1场比赛,占比16.7%
模型模拟次数8
竞技分析开始,共模拟6场比赛
A选手各场次得分比分:
[30, 30, 30, 30, 30, 30]
B选手各场次得分比分:
[7, 10, 18, 8, 17, 20]
选手A获胜6场比赛,占比100.0%
选手B获胜0场比赛,占比0.0%
模型模拟次数8
竞技分析开始,共模拟6场比赛
A选手各场次得分比分:
[20, 21, 21, 23, 21, 30]
B选手各场次得分比分:
[18, 19, 19, 25, 19, 23]
选手A获胜5场比赛,占比83.3%
选手B获胜1场比赛,占比16.7%
模型模拟次数8
竞技分析开始,共模拟6场比赛
A选手各场次得分比分:
[30, 30, 30, 30, 30, 26]
B选手各场次得分比分:
[12, 20, 18, 4, 13, 28]
选手A获胜5场比赛,占比83.3%
选手B获胜1场比赛,占比16.7%
模型模拟次数8
竞技分析开始,共模拟6场比赛
A选手各场次得分比分:
[18, 30, 30, 18, 30, 30]
B选手各场次得分比分:
[20, 21, 15, 20, 18, 19]
选手A获胜4场比赛,占比66.7%
选手B获胜2场比赛,占比33.3%
模型模拟次数8
竞技分析开始,共模拟6场比赛
A选手各场次得分比分:
[30, 30, 30, 20, 28, 30]
B选手各场次得分比分:
[15, 13, 14, 18, 26, 21]
选手A获胜6场比赛,占比100.0%
选手B获胜0场比赛,占比0.0%