Python学记(十四)程序设计方法学(上)

it2022-05-05  90

程序设计方法学

day2019.7.18

体育竞技分析

高手过招,胜负只在毫厘之间 自顶向下 将一个总问题表达为若干个小问题组成的形式,使用同样方法进一步分解小问题 ,直至每一小问题可以利用计算机明了的解决自底向上 # 第一阶段 def main(): printIntro() probA, probB, n = getInputs() winsA, winsB = simNGames(n, probA, probB) printSummary(winsA, winsB) 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("模拟比赛的次数:")) return a, b, n def printSummary(winsA, winsB): n = winsA + winsB print("竞技分析开始,共模拟{}场比赛".format(n)) print("A获胜{}次,占比{:0.1%}".format(winsA, winsA/n)) print("B获胜{}次,占比{:0.1%}".format(winsB, winsB/n)) # 第二阶段 def sinNGames(n, probA, probB): winsA, winsB = 0, 0 for i in range(n): scoreA, scoreB = simOneGame(probA, probB) if scoreA > scoreB: winsA += 1 else: winsB += 1 return winsA, winsB # 第三阶段 def simOneGame(probA, probB): scoreA, socreB = 0, 0 sevring = "A" while not gameOver(scoreA, scoreB): if serving == "A": if random() < probA: socreA += 1 else: serving="B" else: if random() < probB: scoreB += 1 else: serving="A" return socreA, socreB def gameOver(a,b): return a==15 or b==15


最新回复(0)