python石头剪刀布 人(用randint模拟人)vs电脑 共5000次对决,前1000次,公平对决;后4000次,电脑作弊,要求平局的概率是1/3,电脑获胜的概率是5/9,人获胜的概率是1/9;不能直观感受到机器的作弊行为;编写测试程序(用randint模拟人),打印出上述最终概率结果,对代码进行验证
时间: 2024-03-03 12:48:19 浏览: 19
好的,我可以帮你编写这个程序。以下是代码:
```python
import random
win_count = 0
lose_count = 0
tie_count = 0
for i in range(5000):
# 前1000次公平对决
if i < 1000:
player_choice = random.randint(1, 3)
# 后4000次电脑作弊
else:
# 平局概率为1/3
if random.random() < 1/3:
player_choice = random.randint(1, 3)
tie_count += 1
continue
# 电脑获胜概率为5/9
elif random.random() < 5/9:
# 电脑出石头
if player_choice == 1:
player_choice = 2 # 电脑出剪刀
lose_count += 1
# 电脑出剪刀
elif player_choice == 2:
player_choice = 3 # 电脑出布
lose_count += 1
# 电脑出布
else:
player_choice = 1 # 电脑出石头
lose_count += 1
# 人获胜概率为1/9
else:
player_choice = random.randint(1, 3)
win_count += 1
# 判断胜负
computer_choice = random.randint(1, 3)
if player_choice == computer_choice:
tie_count += 1
elif (player_choice == 1 and computer_choice == 2) or \
(player_choice == 2 and computer_choice == 3) or \
(player_choice == 3 and computer_choice == 1):
win_count += 1
else:
lose_count += 1
# 计算最终概率
total_count = win_count + lose_count + tie_count
win_prob = win_count / total_count
lose_prob = lose_count / total_count
tie_prob = tie_count / total_count
# 打印结果
print(f"共进行了{total_count}次对决")
print(f"人获胜的概率为{win_prob:.2f}")
print(f"电脑获胜的概率为{lose_prob:.2f}")
print(f"平局的概率为{tie_prob:.2f}")
```
这个程序用了一个循环来进行5000次对决。前1000次是公平对决,使用`random.randint`来生成人的选择。后4000次是电脑作弊,根据要求的概率来决定电脑的选择。然后程序判断胜负,记录胜负和平局的次数。最后计算出最终的概率,打印出来。
你可以自己运行这个程序,验证代码的正确性。