排球模拟比赛
1 import random 2 def sinCircleGames(n,score,team): 3 '''模拟循环比赛 4 队伍赢得比赛加一分''' 5 for i in range(n): 6 for j in range(i,n): #从第1个队伍依次与每一个队伍打比赛 7 if i ==j: 8 continue 9 else: 10 winI,winJ = sinFiveGame(team[i],team[j]) 11 if winI >winJ: 12 score[i] +=1 13 else: 14 score[j] +=1 15 return score 16 17 def sinFiveGame(probA,probB): 18 "模拟一场五局三胜制比赛" 19 winA,winB =0,0 20 for N in range(5): 21 scoreA,scoreB = sinOneGame(N,probA,probB) 22 if scoreA >scoreB: 23 winA +=1 24 else: 25 winB +=1 26 if winA ==3 or winB ==3: #先得3分者胜 27 break 28 return winA,winB 29 def sinOneGame(N,probA,probB): 30 "模拟1场比赛" 31 scoreA,scoreB = 0,0 32 serving = 'A' #发球方 33 while not gameOver(N,scoreA,scoreB): 34 if serving =='A': 35 if random.random() >probA: #用random函数随机取0~1的数 36 scoreB +=1 37 serving ='B' 38 else: 39 scoreA +=1 40 else: 41 if random.random() >probB: 42 scoreA +=1 43 serving ='A' 44 else: 45 scoreB +=1 46 return scoreA,scoreB 47 48 def gameOver(N,scoreA,scoreB): 49 '''一场比赛结束后结果 50 前四局采用25分制,每个队只有在赢得至少25分,且同时超过对方2分时才胜一局 51 决胜局(第五局)采用15分制,先获得15分,且同时超过对方2分为胜 52 ''' 53 if N <=4: 54 return(scoreA >= 25 and abs(scoreA-scoreB)>=2) or (scoreB >= 25 and abs(scoreA-scoreB)>=2) 55 else: 56 return(scoreA >= 15 and abs(scoreA-scoreB)>=2) or (scoreB >= 15 and abs(scoreA-scoreB)>=2) 57 team = [] 58 teamname = [] 59 score =[] 60 n = int(input("参加比赛的队伍个数:")) 61 for i in range(n): 62 team.append(eval(input("请输入第{}个队伍的能力值".format(i+1)))) 63 teamname.append(i+1) 64 score.append(0) 65 score1 = sinCircleGames(n,score,team) 66 67 dict1 = dict(zip(teamname,score1)) #将队名和分数对应 68 dictionary = sorted(dict1.items(), key = lambda x:x[1],reverse =True) #排序 69 for i in range(n): 70 print("第",dictionary[i][0],"个队伍的得分:",dictionary[i][1]) 71 print('学号:3105')
结果: