import itertools
# 初始化甲和乙的卡片
jia_cards = [1, 3, 5, 7]
yi_cards = [2, 4, 6, 8]
# 初始化计数器
total_rounds = 0
rounds_jia_less_than_2 = 0
# 使用itertools.product模拟所有可能的比赛结果
for round1_jia, round1_yi in itertools.product(jia_cards, yi_cards):
jia_cards.remove(round1_jia) # 甲弃置此轮所选的卡片
yi_cards.remove(round1_yi) # 乙弃置此轮所选的卡片
for round2_jia, round2_yi in itertools.product(jia_cards, yi_cards):
jia_cards.remove(round2_jia)
yi_cards.remove(round2_yi)
for round3_jia, round3_yi in itertools.product(jia_cards, yi_cards):
jia_cards.remove(round3_jia)
yi_cards.remove(round3_yi)
for round4_jia, round4_yi in itertools.product(jia_cards, yi_cards):
jia_cards.remove(round4_jia)
yi_cards.remove(round4_yi)
# 计算甲的总得分
jia_score = sum([1 if a > b else 0 for a, b in zip([round1_jia, round2_jia, round3_jia, round4_jia],
[round1_yi, round2_yi, round3_yi, round4_yi])])
# 更新计数器
total_rounds += 1
if jia_score < 2:
rounds_jia_less_than_2 += 1
# 回溯(还原甲和乙的卡片以便下一轮模拟)
jia_cards.append(round4_jia)
yi_cards.append(round4_yi)
jia_cards.append(round3_jia)
yi_cards.append(round3_yi)
jia_cards.append(round2_jia)
yi_cards.append(round2_yi)
jia_cards.append(round1_jia)
yi_cards.append(round1_yi)
# 计算概率
probability = rounds_jia_less_than_2 / total_rounds
print(f"甲的总得分小于2的概率为:{probability:.4f}") |