python博客作業(yè)2
采用乒乓球比賽規(guī)則
一局比賽:????????????????????????????????????????????????????????????????????????????????????????????????????????????????
???????????????????????????????????????????????????????????????????????????????????????????????????????????????? 在一局比賽中,先得11分的一方為勝方;10平后,先多得2分的一方為勝方。????????????????????????????????????????????????????????????????????????????????????????????????????????????????
??????????????????????????????????????????????????????????????????????????????????????????????????????????????一場(chǎng)比賽:????????????????????????????????????????????????????????????????????????????????????????????????????????????????
????????????????????????????????????????????????????????????????????????????????????????????????????????????? 單打的淘汰賽采用七局四勝制,雙打淘汰賽和團(tuán)體賽采用五局三勝制。
1 from random import random 2 3 def printInfo(): # 打印程序介紹信息 4 print('這個(gè)程序模擬兩個(gè)選手A和B的某種競(jìng)技比賽') 5 print('程序運(yùn)行需要A和B的能力值(以0到1之間的小數(shù)表示)') 6 7 def getInputs(): # 獲得程序運(yùn)行參數(shù) 8 a = eval(input('請(qǐng)輸入選手A的能力值(0-1):')) 9 b = eval(input('請(qǐng)輸入選手B的能力值(0-1):')) 10 n = eval(input('模擬比賽場(chǎng)次(單打淘汰賽為5場(chǎng),雙打淘汰賽為7場(chǎng)):')) 11 return a, b, n 12 13 def simOneGame(probA, probB): # 進(jìn)行一場(chǎng)比賽 14 scoreA, scoreB = 0, 0 # 初始化AB的得分 15 serving = 'A' # 首先由A發(fā)球 16 while not gameOver(scoreA, scoreB): #用while循環(huán)來執(zhí)行比賽 17 if serving == 'A': 18 if random() < probA: # random() 方法返回隨機(jī)生成的一個(gè)實(shí)數(shù),它在[0,1)范圍內(nèi)。 19 scoreA += 1 # 用隨機(jī)數(shù)來和能力值比較從而分出勝負(fù) 20 else: 21 serving = 'B' 22 else: 23 if random() < probB: 24 scoreB += 1 25 else: 26 serving = 'A' 27 return scoreA, scoreB 28 29 def simNGames(n, probA, probB): #進(jìn)行N場(chǎng)比賽 30 winsA, winsB = 0, 0 # 初始化AB的勝場(chǎng)數(shù) 31 for i in range(n): 32 scoreA, scoreB = simOneGame(probA, probB) 33 if scoreA > scoreB: 34 winsA += 1 35 else: 36 winsB += 1 37 return winsA, winsB 38 39 def gameOver(c, d): #比賽結(jié)束 40 return c==11 or d==11 41 42 def printSummary(n ,winA, winB): #打印比賽結(jié)果 43 print('競(jìng)技分析開始,共模擬{}場(chǎng)比賽'.format(n)) 44 print('選手A獲勝{}場(chǎng)比賽,占比{:.2f}%'.format(winA, winA/n*100)) 45 print('選手B獲勝{}場(chǎng)比賽,占比{:.2f}%'.format(winB, winB / n * 100)) 46 def main(): 47 printInfo() 48 probA, probB, n =getInputs() 49 winsA, winsB = simNGames(n, probA, probB) 50 printSummary(n, winsA, winsB) 51 52 print("\n學(xué)號(hào):21\n")53 main()
輸出結(jié)果:
單打淘汰賽5場(chǎng):

雙打淘汰賽7場(chǎng):

posted on 2023-11-19 19:57 伊蕾娜。 閱讀(19) 評(píng)論(0) 收藏 舉報(bào)
浙公網(wǎng)安備 33010602011771號(hào)