Search code examples
pythonloopsfor-loopnested-loops

Looping over multiple foor loops, all posibilities of a dice in Python


I'd like to print all possible options for when rolling n amount of dices. I know how to do this, when hard coding n amount of for loops, however is there a good way of doing so without hard coding a loop for every dice? Preferably without any external libraries.

Here is my Hard coded solution for n = 3, the for loops need to be universalized somehow for any n number:

dices = 3
a = [1]*dices
for a[0] in range(1,7):
    for a[1] in range(1,7):
        for a[2] in range(1,7):
            print(a)

Thanks!


Solution

  • You could also solve it recursively. But itertools.product (proposed by Thierry Lanthuille in the comments) looks like the better choice.

    Here the recursive approach:

    def dices(n, a):
        if n == 0:
            print(a)
            return
        for a[n-1] in range(1,7):
            dices(n-1,a)
            
    dicesCount = 3
    a = [1]*dicesCount
    dices(dicesCount, a)