curriculum/challenges/english/blocks/learn-classes-and-objects-by-building-a-sudoku-solver/660a737f0f72b51de361051c.md
The := operator gives you the ability to assign variables in the middle of an expression. The syntax is: name := val, where name is the variable name and val is the variable value.
This construct is formally named assignment expressions, while the := operator is commonly referred to as the walrus operator.
Since you are going to need the self.find_empty_cell() call more than once, assign it to a variable next_empty by using the walrus operator. Then, enclose the assignment between a pair of parentheses.
In this way, you'll combine the assignment and the conditional check into a single line, making the code more concise.
You should modify the if condition into (next_empty := self.find_empty_cell()) is None.
({ test: () => assert(runPython(`_Node(_code).find_class("Board").find_function("solver").find_ifs()[0].find_conditions()[0].is_equivalent("(next_empty := self.find_empty_cell()) is None")`)) })
class Board:
def __init__(self, board):
self.board = board
def find_empty_cell(self):
for row, contents in enumerate(self.board):
try:
col = contents.index(0)
return row, col
except ValueError:
pass
return None
def valid_in_row(self, row, num):
return num not in self.board[row]
def valid_in_col(self, col, num):
return all(self.board[row][col] != num for row in range(9))
def valid_in_square(self, row, col, num):
row_start = (row // 3) * 3
col_start = (col // 3) * 3
for row_no in range(row_start, row_start + 3):
for col_no in range(col_start, col_start + 3):
if self.board[row_no][col_no] == num:
return False
return True
def is_valid(self, empty, num):
row, col = empty
valid_in_row = self.valid_in_row(row, num)
valid_in_col = self.valid_in_col(col, num)
valid_in_square = self.valid_in_square(row, col, num)
return all([valid_in_row, valid_in_col, valid_in_square])
--fcc-editable-region--
def solver(self):
if self.find_empty_cell() is None:
return True
--fcc-editable-region--
puzzle = [
[0, 0, 2, 0, 0, 8, 0, 0, 0],
[0, 0, 0, 0, 0, 3, 7, 6, 2],
[4, 3, 0, 0, 0, 0, 8, 0, 0],
[0, 5, 0, 0, 3, 0, 0, 9, 0],
[0, 4, 0, 0, 0, 0, 0, 2, 6],
[0, 0, 0, 4, 6, 7, 0, 0, 0],
[0, 8, 6, 7, 0, 4, 0, 0, 0],
[0, 0, 0, 5, 1, 9, 0, 0, 8],
[1, 7, 0, 0, 0, 6, 0, 0, 5]
]
gameboard = Board(puzzle)