views:

111

answers:

3

I know about itertools, but it seems it can only generate permutations without repetitions.

for example, I'd like to generate all possible dice rolls for 2 dice. So I need all permutations of size 2 of [1, 2, 3, 4, 5, 6] including repetitions: (1, 1), (1, 2), (2, 1)... etc

If possible I don't want to implement this from scratch

+5  A: 

You are looking for the Cartesian Product.

In mathematics, a Cartesian product (or product set) is the direct product of two sets.

In your case, this would be {1, 2, 3, 4, 5, 6} x {1, 2, 3, 4, 5, 6}. itertools can help you there:

import itertools
x = [1, 2, 3, 4, 5, 6]
[p for p in itertools.product(x, repeat=2)]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3), 
 (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), 
 (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), 
 (5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]

To get a random dice roll (inefficently):

import random
random.choice([p for p in itertools.product(x, repeat=2)])
(6, 3)
The MYYN
Rewrote my post.
The MYYN
This is an extremely inefficient way of getting 2 dice rolls… Two calls to `random.randint` would be simpler and more efficient.
EOL
Random dice rolls will be much faster when you don't generate all possible pairs: [random.randint(1,6) for i in xrange(2)]
liori
+ for `product(…, repeat=…)`.
EOL
I wasn't actually trying to generate random rolls, just to list all possible rolls.
Bwmat
+9  A: 

You're not looking for permutations - you want the Cartesian Product. For this use product from itertools:

from itertools import product
for roll in product([1, 2, 3, 4, 5, 6], repeat = 2):
    print(roll)
Mark Byers
You can more simply do `product(die, repeat=2)`: there is no need for the `dice` list.
EOL
Good point, thanks.
Mark Byers
+1  A: 

In python 2.7 and 3.1 there is a itertools.combinations_with_replacement function:

>>> list(itertools.combinations_with_replacement([1, 2, 3, 4, 5, 6], 2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 2), (2, 3), (2, 4), 
 (2, 5), (2, 6), (3, 3), (3, 4), (3, 5), (3, 6), (4, 4), (4, 5), (4, 6),
 (5, 5), (5, 6), (6, 6)]
SilentGhost