python - 如何存储从多个列表生成的随机整数
问题描述
我正在尝试编写一个脚本来模拟非常规骰子的骰子游戏。游戏的目的是根据重复实验确定哪个骰子更好,其中较大的数字/滚动获胜。这是我到目前为止的工作示例:
from random import randint, seed
from datetime import datetime
import itertools as it
seed(datetime.now())
def find_the_best_dice(dices):
assert all(len(dice) == 6 for dice in dices)
for dice1, dice2 in it.combinations(dices, 2):
num_rounds = 100
num_dice1_wins = 0
num_dice2_wins = 0
for _ in range(num_rounds):
dice1_result = dice1[randint(0, 5)]
dice2_result = dice2[randint(0, 5)]
if dice1_result > dice2_result:
num_dice1_wins += 1
elif dice2_result > dice1_result:
num_dice2_wins += 1
return ("index of winning dice or -1 if tie")
find_the_best_dice(dices=[[1, 1, 6, 6, 8, 8], [2, 2,
4, 4, 9, 9], [3, 3, 5, 5, 7, 7]])
我面临的问题是不知道如何存储超过 2 个骰子的获胜次数。
解决方案
通常,我会为这样的事情使用字典,但由于您对骰子的表示是一个列表(不可散列),您可以将它们转换为 afrozenset
或 a tuple
。我更喜欢元组,因为它保留了顺序和重复(如果有的话)。
num_rounds = 100
dice_wins = {tuple(x):0 for x in dices}
for dice1, dice2 in it.combinations(dices, 2):
for _ in range(num_rounds):
dice1_result = dice1[randint(0, 5)]
dice2_result = dice2[randint(0, 5)]
if dice1_result > dice2_result:
dice_wins[tuple(dice1)] += 1
elif dice2_result > dice1_result:
dice_wins[tuple(dice2)] += 1
max_win = max(list(dice_wins.values()))
die_with_max_win = [dice for dice in dices if dice_wins[tuple(dice)] == max_win]
if len(die_with_max_win) == 1:
return die_with_max_win[0] # only dice with that many wins
else:
return -1 # more than one dice with max wins
希望这可以帮助!
推荐阅读
- mysql - 如何将 MySQL 数据库连接到 Moqui?
- grpc - Grpc C++:如何等到一元请求被发送?
- java - List 方法结合初始化一个新对象
- r - 单元测试 - 比较环境
- javascript - 尝试在 next.js 应用程序中运行下一个构建时出现错误
- c# - 我应该避免使用 C#“is”运算符进行相等检查吗?
- laravel - 使用“php artisan migrate”命令时 Laravel 数据库迁移外键错误
- yocto - bitbake core-image-minimal 失败并显示消息:No module named 'pyshtables'
- string - 使用 pixi-multistyle-text Pixi.js - 更改字符串中的字符颜色
- python - Pandas 按日期条件计数