预测体育竞技比赛结果(新人练手)
作者:互联网
一、模拟体育比赛分析
例:乒乓球设规则如下:
一局比赛中: 先赢得11分为胜 10平后 先多赢得2分为胜
单打淘汰赛 :7句4胜
代码如下
1 # -*- coding: utf-8 -*- 2 """ 3 Created on Wed May 15 11:38:02 2019 4 5 @author: lenovo 6 """ 7 8 import random 9 import math 10 def printIntro(): 11 print("这个程序模拟量个选手A和B的乒乓球比赛") 12 print("程序运行需要A和B的能力值(以0到1之间的小数表示)") 13 print("作者:呆。 (02)") 14 def getInputs(): 15 a = eval(input("请输入选手A的能力值(0-1): ")) 16 b = eval(input("请输入选手B的能力值(0-1): ")) 17 n = eval(input("模拟比赛的场次: ")) 18 return a, b, n 19 20 def printSummary(winsA, winsB): 21 n = winsA + winsB 22 print("竞技分析开始, 共模拟{}场比赛".format(n)) 23 print("选手A获胜{}场比赛, 占比{:0.1%}".format(winsA, winsA/n)) 24 print("选手B获胜{}场比赛, 占比{:0.1%}".format(winsB, winsB/n)) 25 26 def gameOver(a, b): 27 return (a==11 and b<10) or (b==11 and a<10) or (a>=10 and b>=10 and math.fabs(a-b)==2) 28 29 def simoneGame(probA, probB): 30 scoreA, scoreB = 0, 0 31 if random.random() < 0.5: 32 serving = "A" 33 else : 34 serving = "B" 35 while not gameOver(scoreA, scoreB): 36 if serving == "A": 37 if random.random() < probA: 38 scoreA += 1 39 else: 40 serving = "B" 41 else: 42 if random.random() < probB: 43 scoreB += 1 44 else: 45 serving = "A" 46 return scoreA, scoreB 47 def simOneGame(probA, probB): 48 winsA, winsB = 0, 0 49 for i in range(7): 50 scoreA, scoreB = simoneGame(probA, probB) 51 if scoreA > scoreB: 52 winsA += 1 53 else: 54 winsB += 1 55 return winsA, winsB 56 def simNGames(n ,probA, probB): 57 winsA, winsB = 0, 0 58 for i in range(n): 59 scoreA, scoreB = simOneGame(probA, probB) 60 if scoreA > scoreB: 61 winsA += 1 62 else: 63 winsB += 1 64 return winsA, winsB 65 66 def main(): 67 printIntro() 68 probA, probB, n = getInputs() 69 winsA, winsB = simNGames(n, probA, probB) 70 printSummary(winsA, winsB) 71 main()
结果如下:
标签:练手,winsB,winsA,scoreA,比赛结果,probB,probA,体育竞技,def 来源: https://www.cnblogs.com/DXL123/p/10869735.html