Search code examples
pythonpermutationpython-itertools

Permutations with repetition given a number of dices


I was looking for a solution on Internet, but could not find an answer, mostly due to my poor English (I could not ask a correct question).

I need to generate a list of all possible permutations (combinations) of dices given a number of dices.

For example, 2 dices should give me the following list:

[(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)]

I was thinking of using itertools as the following code:

from itertools import permutations

perm = permutations([1, 2, 3, 4, 5, 6], 2)

print(list(perm))

However, when I run it, I get exactly the same results as needed, but without repeating numbers:

[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)]

I could also use the following code:

lst = []

for i in list(range(1,7)):
    for j in list(range(1,7)):
        lst.append([i, j])
                  
print(lst)

... but I would have to rely in the advance knowledge of how many dices I am using.

I hope I could explain my issue correctly. I am sorry for my English.


Solution

  • What you are looking for is called a Cartesian Product. itertools has a method called product which does this for you.

    In your case you would use it like so:

    from itertools import product
    prod = product([1,2,3,4,5,6], repeat=2)
    
    print(list(prod))