Python solution using dictionaries 76 ms, also a question about syntax


  • 0
    D
    class Solution(object):
        def isValidSudoku(self, board):
            """
            :type board: List[List[str]]
            :rtype: bool
            """
            
            rows = {}
            columns = {}
            squares = {}
            # can be done with defaultdict as well:
            for n in range(9):
                rows[n] = set()
                columns[n] = set()
                squares[n] = set()
            
            for r in range(9):
                for c in range(9):
                    num = board[r][c]
                    if num == '.':
                        continue
                    s = (r/3)*3 + c/3
                    if num in rows[r] or num in columns[c] or num in squares[s]:
                        return False
                    rows[r].add(num)
                    columns[c].add(num)
                    squares[s].add(num)
            
            return True
    

    My question is if there is any other syntax to initialize multiple variables to empty dictionaries? I tried the multiple equal sign syntax rows = columns = squares = {}, but it appears that this just creates one dictionary that can be referenced by three names. I was having trouble because rows[r].add(num) was also performing columns[r].add(num) and squares[r].add(num). Also in the for loop, I couldn't just do rows[n] = columns[n] = squares[n] = set() either. The code behaved very weirdly when I did so. Can someone explain what the multiple equal sign syntax does exactly in this context?


  • 0
    This post is deleted!

  • 2

    You're right, it assigns the same single dict object to three variables. One thing you can do is this:

    rows, columns, squares = {}, {}, {}
    

    Or for example:

    rows, columns, squares = ({i: set() for i in range(9)}
                              for _ in range(3))

  • 0
    D

    Ah your second piece of code is quite a clean way to do what I did in 7 lines. Nice.


Log in to reply
 

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