是否有一种优雅的方式来迭代最多五个骰子的可能骰子?
我想替换这个hacky Python:
self.rolls[0] = [str(a) for a in range(1,7)]
self.rolls[1] = [''.join([str(a), str(b)])
for a in range(1, 7)
for b in range(1, 7)
if a <= b]
self.rolls[2] = [''.join([str(a), str(b), str(c)])
for a in range(1, 7)
for b in range(1, 7)
for c in range(1, 7)
if a <= b <= c]
self.rolls[3] = [''.join([str(a), str(b), str(c), str(d)])
for a in range(1, 7)
for b in range(1, 7)
for c in range(1, 7)
for d in range(1, 7)
if a <= b <= c <= d]
self.rolls[4] = [''.join([str(a), str(b), str(c), str(d), str(e)])
for a in range(1, 7)
for b in range(1, 7)
for c in range(1, 7)
for d in range(1, 7)
for e in range(1, 7)
if a <= b <= c <= d <= e]
答案 0 :(得分:30)
您可以使用itertools
'combinations_with_replacement
。
例如,使用3个4面骰子(仅因为输出太大):
>>> from itertools import combinations_with_replacement
>>> dice = 3
>>> faces = 4
>>> list(combinations_with_replacement(range(1, faces+1), dice))
[(1, 1, 1),
(1, 1, 2),
(1, 1, 3),
(1, 1, 4),
(1, 2, 2),
(1, 2, 3),
(1, 2, 4),
(1, 3, 3),
(1, 3, 4),
(1, 4, 4),
(2, 2, 2),
(2, 2, 3),
(2, 2, 4),
(2, 3, 3),
(2, 3, 4),
(2, 4, 4),
(3, 3, 3),
(3, 3, 4),
(3, 4, 4),
(4, 4, 4)]