首页 > 解决方案 > 如何存储从多个列表生成的随机整数

问题描述

我正在尝试编写一个脚本来模拟非常规骰子的骰子游戏。游戏的目的是根据重复实验确定哪个骰子更好,其中较大的数字/滚动获胜。这是我到目前为止的工作示例:

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 个骰子的获胜次数。

标签: pythondice

解决方案


通常,我会为这样的事情使用字典,但由于您对骰子的表示是一个列表(不可散列),您可以将它们转换为 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

希望这可以帮助!


推荐阅读