Sudoku Checker in Python

Discussion in 'Python' started by lionaneesh, Mar 11, 2012.

  1. lionaneesh

    lionaneesh Active Member

    Joined:
    Mar 21, 2010
    Messages:
    848
    Likes Received:
    224
    Trophy Points:
    43
    Occupation:
    Student
    Location:
    India
    Sudoku is a logic based number-placement puzzle, The objective of the puzzle is to fill a n * n grid with digits so that :-

    • Each column of the square contains each of the numbers from 1 to n exactly once.
    • Each row of the square contains each of the numbers from 1 to n exactly once.

    The Code



    Code:
    correct = [[1,3,2],
               [2,1,3],
               [3,2,1]]
    
    incorrect = [[1,2,4,3],
                 [2,3,1,3],
                 [3,1,2,3],
                 [4,2,2,4]]
    
    
    def check_sudoku(game):
        n = len(game)
        if n < 1:
            return False
        for i in range(0, n):
            horizontal = []
            vertical = []
            for k in range(0, n):
                #vertical check
                if game[k][i] in vertical:
                    return False
                vertical.append(game[k][i])
    
                if game[i][k] in horizontal:
                    return False
                horizontal.append(game[i][k])
        return True
    
    print check_sudoku(correct)
    print check_sudoku(incorrect)
    
    Output :-

    Code:
    True
    False
    

    Conclusion



    The above code would work for any sudoku grid, like 3 x 3, 4 x 4, 9 x 9 etc. Now next time someone asks you to check his/her solved sudoku just feed that into this program and give them the answer :), That's easy :pleased: isn't it?
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice