2016-01-19 11 views
15

ダイスロールを5回まで繰り返すことができるエレガントな方法はありますか?エレガントなPythonダイス反復を求める

私はこのハックの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] 

答えて

30

あなたはitertools "combinations_with_replacementを使用することができます。

>>> 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)] 
:(出力 すぎ大きくないという理由だけで)3 4面ダイスと例えば