Back to Freecodecamp

Step 46

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

latest2.1 KB
Original Source

--description--

Within the Board class, create another method is_valid and give it three parameters: self, empty, and num. Where empty is a tuple representing the row and column indices of an empty cell and num is the number to be checked.

This method will check if a given number is a valid choice for an empty cell in the sudoku board by validating its compatibility with the row, column, and 3x3 square of the specified empty cell.

--hints--

You should create a new method named is_valid within the Board class.

js
({ test: () => assert(runPython(`_Node(_code).find_class("Board").has_function("is_valid")`)) })

Your is_valid method should have three parameters: self, empty, and num, in this order.

js
({ test: () => assert(runPython(`_Node(_code).find_class("Board").find_function("is_valid").has_args("self, empty, num")`)) })

--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))

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