模拟体育竞技分析

import random

def simulate_game(prob_a, prob_b):
"""模拟一局比赛,返回胜者(A或B)"""
score_a, score_b = 0, 0
while True:
# 随机决定得分方,prob_a为A得分概率
if random.random() < prob_a:
score_a += 1
else:
score_b += 1

    # 判断胜负条件:先得11分,或10平后多2分
    if score_a >= 11 or score_b >= 11:
        if abs(score_a - score_b) >= 2:
            return 'A' if score_a > score_b else 'B'

def simulate_set(prob_a, prob_b, set_type):
"""模拟一场比赛(多局),返回胜者(A或B)"""
if set_type == 'single': # 单打七局四胜
target = 4
else: # 双打/团体五局三胜
target = 3

wins_a, wins_b = 0, 0
while wins_a < target and wins_b < target:
    game_winner = simulate_game(prob_a, prob_b)
    if game_winner == 'A':
        wins_a += 1
    else:
        wins_b += 1

return 'A' if wins_a > wins_b else 'B'

def run_simulation(prob_a, prob_b, num_simulations, set_type):
"""运行多次模拟,统计胜率"""
wins_a = 0
for _ in range(num_simulations):
match_winner = simulate_set(prob_a, prob_b, set_type)
if match_winner == 'A':
wins_a += 1

win_rate_a = wins_a / num_simulations
win_rate_b = 1 - win_rate_a
return win_rate_a, win_rate_b

def main():
"""主函数:获取输入并执行模拟"""
try:
prob_a = float(input("请输入A选手的得分概率(0-1): "))
if not (0 <= prob_a <= 1):
print("概率必须在0到1之间!")
return

    num_simulations = int(input("请输入模拟次数: "))
    if num_simulations <= 0:
        print("模拟次数必须为正整数!")
        return
    
    set_type = input("请输入比赛类型(single为单打,其他为双打/团体): ")
    
    win_rate_a, win_rate_b = run_simulation(prob_a, 1 - prob_a, num_simulations, set_type)
    
    print(f"模拟{num_simulations}次比赛的结果:")
    print(f"A选手的胜率: {win_rate_a:.2%}")
    print(f"B选手的胜率: {win_rate_b:.2%}")
    
except ValueError:
    print("输入格式错误,请输入有效的数字!")

if name == "main":
main()

posted @ 2025-06-23 13:44  kkkk0515  阅读(29)  评论(0)    收藏  举报