人狼羊菜问题python代码求解
时间: 2024-11-12 14:04:06 浏览: 30
人狼羊菜问题是经典的逻辑推理游戏,通常用于讲解概率和假设检验的概念。在Python中,你可以通过模拟多个回合的游戏来进行求解。以下是一个简单的版本的代码:
```python
import random
def game(players, wolves, shepherds):
villagers = players - (wolves + shepherds)
roles = ['human', 'wolf', 'shepherd'] * players
for _ in range(10): # 假设每个人每天都会发言,共10天
if wolves > 0 and random.choice(roles) == 'shepherd':
# 羊吃掉一只狼
wolves -= 1
elif wolves > 0 and random.choice(roles) == 'human':
# 如果有狼并且村民猜对了,则村民被狼吃掉
villagers -= 1
else:
# 没有狼或羊,随机选择一个人死亡
villagers -= 1
# 清除已知角色身份的人
roles = [r for r in roles if r != 'human' if r != 'wolf' if r != 'shepherd']
return wolves, villagers
# 示例:初始人数、狼的数量和牧羊人的数量
num_players = 5
wolves = 2
shepherds = 1
end_state = game(num_players, wolves, shepherds)
print(f"最后剩下狼{end_state[0]}只,村民{end_state[1]}人")
阅读全文