1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Sudoku Checker in Python

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

  1. lionaneesh

    lionaneesh New Member

    Joined:
    Mar 21, 2010
    Messages:
    848
    Likes Received:
    224
    Trophy Points:
    0
    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