Back to Freecodecamp

Step 41

curriculum/challenges/english/blocks/learn-classes-and-objects-by-building-a-sudoku-solver/6606d378de78d55523f08298.md

latest2.1 KB
Original Source

--description--

Now, check if the given number num is already present in the current cell of the 3x3 square.

Replace pass with an if statement that checks if the number in the current cell of the sudoku board is equal to num. If so, return False from the if body, indicating that the number is not a valid choice.

--hints--

You should delete pass and create an if statement that checks if the current cell of the sudoku board is equal to num.

js
({ test: () => assert(runPython(`_Node(_code).find_class("Board").find_function("valid_in_square").find_for_loops()[0].find_for_loops()[0].find_ifs()[0].find_conditions()[0].is_equivalent("self.board[row_no][col_no] == num")`)) })

You should return False from your new if statement body.

js
({ test: () => assert(runPython(`_Node(_code).find_class("Board").find_function("valid_in_square").find_for_loops()[0].find_for_loops()[0].find_ifs()[0].find_bodies()[0].is_equivalent("return False")`)) })

--seed--

--seed-contents--

py
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))
--fcc-editable-region--
    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):
                pass
--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)