Back to Freecodecamp

Step 48

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

latest1.9 KB
Original Source

--description--

Within the is_valid method, check if the number is valid for insertion in the specified row by calling the valid_in_row() method with row and num as arguments, and assign the result to a variable valid_in_row. Remember to use self to reference the methods of the current instance.

--hints--

You should declare a variable valid_in_row and assign it self.valid_in_row(row, num).

js
({ test: () => assert(runPython(`_Node(_code).find_class("Board").find_function("is_valid").find_variable("valid_in_row").is_equivalent("valid_in_row = self.valid_in_row(row, 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--
    def is_valid(self, empty, num):
        row, col = empty
--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)