A readable Python solution


  • 33
    C

    Apparently not the shortest solution but I think it's easy to follow the logic.

    def isValidSudoku(self, board):
        return (self.is_row_valid(board) and
                self.is_col_valid(board) and
                self.is_square_valid(board))
    
    def is_row_valid(self, board):
        for row in board:
            if not self.is_unit_valid(row):
                return False
        return True
    
    def is_col_valid(self, board):
        for col in zip(*board):
            if not self.is_unit_valid(col):
                return False
        return True
        
    def is_square_valid(self, board):
        for i in (0, 3, 6):
            for j in (0, 3, 6):
                square = [board[x][y] for x in range(i, i + 3) for y in range(j, j + 3)]
                if not self.is_unit_valid(square):
                    return False
        return True
        
    def is_unit_valid(self, unit):
        unit = [i for i in unit if i != '.']
        return len(set(unit)) == len(unit)

  • 0
    J

    I think this version is more acceptable in the interview. thanks.


  • 0
    S

    Thanks for your solution! But what is the running time of the function "is_square_valid(self, board)"? It seems to have 4 for loops.


  • 0

    This is a way better answer in terms of readability


  • 0
    T

    @ChuntaoLu
    It's a great solution though. Thanks. I just want to modify a bit using nested function of python.

     def isValidSudoku(self, board):
        def is_valid_row(board):
            for row in board:
                if not is_valid(row):
                    return False
            return True
            
        def is_valid_column(board):
            for col in zip(*board): 
                if not is_valid(col):
                    return False
            return True
            
        def is_valid_square(board):
            for i in (0,3,6):
                for j in (0,3,6):
                    square = [board[x][y] for x in range(i,i+3) 
                                            for y in range(j,j+3)]
                    if not is_valid(square):
                        return False
            return True
        
        def is_valid(value):
            res = [i for i in value if i != '.']
            return len(res) == len(set(res))
        
        return is_valid_row(board) and is_valid_column(board) and is_valid_square(board)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.