Skip to content

Commit 0d358b7

Browse files
authored
Simplify sudoku.is_completed() using builtin all()
Simplify __sudoku.is_completed()__ using Python builtin function [__all()__](https://docs.python.org/3/library/functions.html#all).
1 parent 74aeaa3 commit 0d358b7

File tree

1 file changed

+2
-18
lines changed

1 file changed

+2
-18
lines changed

backtracking/sudoku.py

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
"""
2-
32
Given a partially filled 9×9 2D array, the objective is to fill a 9×9
43
square grid with digits numbered 1 to 9, so that every row, column, and
54
and each of the nine 3×3 sub-grids contains all of the digits.
@@ -9,9 +8,7 @@
98
function on the next column to see if it returns True. if yes, we
109
have solved the puzzle. else, we backtrack and place another number
1110
in that cell and repeat this process.
12-
1311
"""
14-
1512
# assigning initial values to the grid
1613
initial_grid = [
1714
[3, 0, 6, 5, 0, 8, 4, 0, 0],
@@ -24,6 +21,7 @@
2421
[0, 0, 0, 0, 0, 0, 0, 7, 4],
2522
[0, 0, 5, 2, 0, 6, 3, 0, 0],
2623
]
24+
2725
# a grid with no solution
2826
no_solution = [
2927
[5, 0, 6, 5, 0, 8, 4, 0, 3],
@@ -44,9 +42,7 @@ def is_safe(grid, row, column, n):
4442
column, and the 3x3 subgrids contain the digit 'n'.
4543
It returns False if it is not 'safe' (a duplicate digit
4644
is found) else returns True if it is 'safe'
47-
4845
"""
49-
5046
for i in range(9):
5147
if grid[row][i] == n or grid[i][column] == n:
5248
return False
@@ -64,24 +60,15 @@ def is_completed(grid):
6460
This function checks if the puzzle is completed or not.
6561
it is completed when all the cells are assigned with a number(not zero)
6662
and There is no repeating number in any column, row or 3x3 subgrid.
67-
6863
"""
69-
70-
for row in grid:
71-
for cell in row:
72-
if cell == 0:
73-
return False
74-
75-
return True
64+
return all(cell != 0 for cell in row for row in grid)
7665

7766

7867
def find_empty_location(grid):
7968
"""
8069
This function finds an empty location so that we can assign a number
8170
for that particular row and column.
82-
8371
"""
84-
8572
for i in range(9):
8673
for j in range(9):
8774
if grid[i][j] == 0:
@@ -129,17 +116,14 @@ def print_solution(grid):
129116
"""
130117
A function to print the solution in the form
131118
of a 9x9 grid
132-
133119
"""
134-
135120
for row in grid:
136121
for cell in row:
137122
print(cell, end=" ")
138123
print()
139124

140125

141126
if __name__ == "__main__":
142-
143127
# make a copy of grid so that you can compare with the unmodified grid
144128
for grid in (initial_grid, no_solution):
145129
grid = list(map(list, grid))

0 commit comments

Comments
 (0)