Search code examples
python-3.xcombinationspython-itertoolscombinatoricssudoku

Generate all combinations of a list of n^2 elements with each element being from 1 to n?


I am trying to enumerate the number of valid sudokus of a given size. I have a function that takes a sudoku transformed into a list as input and checks to see if it is a valid sudoku or not. My original method was just to write nested for loops to check every single combination of a list. For a 2 x 2 sudoku, my code looks something like this:

def enumerate2x2():

cnt = 0

for i1 in range(1,3):
    for i2 in range(1,3):
        for i3 in range(1,3):
            for i4 in range(1,3):
                if checkValidSudoku([i1, i2, i3, i4]):
                    cnt += 1

print(cnt)

This code just generates every possible combination of a 4-element list (that's how many squares are in a 2x2 sudoku) with each element in the list being either a 1 or a 2. It then checks each combination.

However, when trying this on a 5x5 sudoku i ran into a problem as python only allows you to have 20 nested loops, so I want to generalize this ugly method into something that will work with any size sudoku. Any help would be appreciated.


Solution

  • The Python product intrinsic function, just importing the itertools module, is what you need:

    import itertools
    
    sudoku = list(itertools.product(range(1,3), repeat=4))
    
    for x in range(len(sudoku)):
         print sudoku[x]
    
    

    that simply calculate all the cartesian products, you were looking for, here below the output:

    (1, 1, 1, 1)
    (1, 1, 1, 2)
    (1, 1, 2, 1)
    (1, 1, 2, 2)
    (1, 2, 1, 1)
    (1, 2, 1, 2)
    (1, 2, 2, 1)
    (1, 2, 2, 2)
    (2, 1, 1, 1)
    (2, 1, 1, 2)
    (2, 1, 2, 1)
    (2, 1, 2, 2)
    (2, 2, 1, 1)
    (2, 2, 1, 2)
    (2, 2, 2, 1)
    (2, 2, 2, 2)
    

    it seems no combination is now missing, isn't it? Have a look at this other question Combinations with repetition in python, where order MATTERS for more details on alternative implementation too.