学习目标
体育竞技分析实例:
设规则如下:
Python 3.x 代码(自顶向下的设计方法)如下:
1 #两个选手A,B的羽毛球竞技比赛预测 2 from random import random 3 def printIntro(): 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 m = eval(input("模拟次数:")) 11 return a, b, n, m 12 def simNGames(n, probA, probB): 13 winsA, winsB = 0, 0 14 scoreA_ls=[] 15 scoreB_ls=[] 16 for i in range(n): 17 scoreA, scoreB = simOneGame(probA, probB) 18 scoreA_ls.append(scoreA) 19 scoreB_ls.append(scoreB) 20 if scoreA > scoreB: 21 winsA += 1 22 else: 23 winsB += 1 24 return winsA, winsB,scoreA_ls,scoreB_ls 25 def gameOver(a,b): 26 if(a>=20 or b>=20): 27 if(abs(a-b)==2 and a<=29 and b<=29): 28 return True 29 else: 30 return a==30 or b==30 31 else: 32 return False 33 def simOneGame(probA, probB): 34 scoreA, scoreB = 0, 0 35 serving = "A" 36 while not gameOver(scoreA, scoreB): 37 if serving == "A": 38 if random() < probA: 39 scoreA += 1 40 else: 41 serving="B" 42 else: 43 if random() < probB: 44 scoreB += 1 45 else: 46 serving="A" 47 return scoreA, scoreB 48 def printSummary(winsA, winsB,scoreA_ls,scoreB_ls): 49 n = winsA + winsB 50 print("竞技分析开始,共模拟{}场比赛".format(n)) 51 print("A选手各场次得分比分:") 52 print(scoreA_ls) 53 print("B选手各场次得分比分:") 54 print(scoreB_ls) 55 print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA, winsA/n)) 56 print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB, winsB/n)) 57 def main(): 58 printIntro() 59 probA, probB, n, m= getInputs() 60 for i in range(m): 61 winsA, winsB,scoreA_ls,scoreB_ls = simNGames(n, probA, probB) 62 printSummary(winsA, winsB,scoreA_ls,scoreB_ls) 63 64 main()
运行结果如下:
1 这个程序模拟两个选手A和B的羽毛球竞技比赛 2 程序运行需要A和B的能力值(以0到1之间的小数表示) 3 4 请输入选手A的能力值(0-1): 0.5 5 6 请输入选手B的能力值(0-1): 0.5 7 8 模拟比赛的场次: 5 9 10 模拟次数:5 11 竞技分析开始,共模拟5场比赛 12 A选手各场次得分比分: 13 [18, 20, 24, 20, 30] 14 B选手各场次得分比分: 15 [20, 18, 22, 18, 24] 16 选手A获胜4场比赛,占比80.0% 17 选手B获胜1场比赛,占比20.0% 18 竞技分析开始,共模拟5场比赛 19 A选手各场次得分比分: 20 [21, 23, 19, 30, 30] 21 B选手各场次得分比分: 22 [19, 25, 21, 21, 17] 23 选手A获胜3场比赛,占比60.0% 24 选手B获胜2场比赛,占比40.0% 25 竞技分析开始,共模拟5场比赛 26 A选手各场次得分比分: 27 [20, 20, 18, 19, 30] 28 B选手各场次得分比分: 29 [18, 18, 30, 30, 11] 30 选手A获胜3场比赛,占比60.0% 31 选手B获胜2场比赛,占比40.0% 32 竞技分析开始,共模拟5场比赛 33 A选手各场次得分比分: 34 [20, 19, 30, 26, 23] 35 B选手各场次得分比分: 36 [18, 21, 20, 28, 21] 37 选手A获胜3场比赛,占比60.0% 38 选手B获胜2场比赛,占比40.0% 39 竞技分析开始,共模拟5场比赛 40 A选手各场次得分比分: 41 [18, 30, 21, 30, 30] 42 B选手各场次得分比分: 43 [20, 7, 19, 18, 16] 44 选手A获胜4场比赛,占比80.0% 45 选手B获胜1场比赛,占比20.0%
使用pyinstaller对上述代码文件打包成可执行文件(可在没有安装Python的环境中运行)
方法如下:
C:\Users\Benny>pip install pyinstaller
打包
:\>pyisntaller dpython.py 或
:\>pyinstaller D:\codes\dpython.py
生成一个独立可执行文件
:\>pyinstaller -F dpython.py
原文:https://www.cnblogs.com/shuxincheng/p/10856136.html