Back to Freecodecamp

Step 39

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

latest1.7 KB
Original Source

--description--

Now, iterate only over the rows inside the 3x3 square by creating a for loop. Use the range() function to generate a sequence starting at row_start, and use row_no as the loop variable.

--hints--

You should create a for loop that iterates over range(row_start, row_start + 3).

js
({ test: () => assert(runPython(`_Node(_code).find_class("Board").find_function("valid_in_square").find_for_loops()[0].find_for_iter().is_equivalent("range(row_start, row_start + 3)")`)) })

Your for loop should use row_no as the loop variable.

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

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