【问题标题】:Get sublist of n elements from unique permutations of a list从列表的唯一排列中获取 n 个元素的子列表
【发布时间】:2021-11-23 20:24:44
【问题描述】:

我正在编写代码以将不同边数的骰子掷在一起。主函数接受 2 个数字的列表,这些数字代表骰子的面数,例如[4, 6] — 表示程序将使用 d4 和 d6 执行操作。

问题来了:

我有一个要使用的所有不同类型骰子的列表[4, 6, 8, 10, 12, 20],我需要一些代码来找出每个唯一的 2 个骰子组来传递,而不是以不同的顺序传递同一个骰子,例如:不要同时传入[4, 6] 和[6, 4]。

我计划将来扩展该程序以一次掷n 骰子,例如5d4 和 2d20 所以不仅适用于 2 个骰子的代码将不胜感激。

最后,我希望能够掷出两个相同的骰子,例如:[4, 4]。

如果问题需要更多解释,请告诉我。

【问题讨论】:

  • itertools.combinations_with_replacement(dice, 2)
  • 我认为应该是 itertools.combinations_with_replacement 以允许 [4, 4] 和类似的。

标签: python unique permutation dice


【解决方案1】:

使用来自itertools 库的combinations_with_replacements。

from itertools import combinations_with_replacement

dice = [4, 6, 8, 10, 12, 20]
N_dice = 2

print(list(combinations_with_replacement(dice, N_dice)))

给出输出

[(4, 4), (4, 6), (4, 8), (4, 10), (4, 12), (4, 20), (6, 6), (6, 8), (6, 10), (6, 12), (6, 20), (8, 8), (8, 10), (8, 12), (8, 20), (10, 10), (10, 12), (10, 20), (12, 12), (12, 20), (20, 20)]

【讨论】:

    【解决方案2】:

    d20 包就是这样做的。见https://pypi.org/project/d20/。

    这是一个使用示例:

    d20.roll("1d12+3d8+4d6+14").total
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      相关资源
      最近更新 更多