-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku.py
101 lines (81 loc) · 2.72 KB
/
sudoku.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
"""
Validate sudoku game state
"""
def get_first_duplicate(xs):
for x in xs:
positive_x = abs(x)
positive_x_index = positive_x - 1
xs[positive_x_index] *= -1
if xs[positive_x_index] > 0:
return positive_x
return -1
def matrix_print(matrix):
result = ''
for row in matrix:
for val in row:
result += '{:4}'.format(val)
result += '\n'
print(result)
def is_valid_sudoku_seq(seq):
xs = list(filter(lambda x: x != '.', seq))
return len(xs) == len(set(xs))
def sudoku2(grid):
n = len(grid)
# get rows
for row in grid:
is_valid = is_valid_sudoku_seq(row)
if not is_valid:
return False
for i in range(n):
col = [row[i] for row in grid]
is_valid = is_valid_sudoku_seq(col)
if not is_valid:
return False
for i in range(3):
rows = grid[3*i:3*i+3]
for j in range(3):
subgrid = sum([row[j*3:j*3 + 3] for row in rows], [])
is_valid = is_valid_sudoku_seq(subgrid)
if not is_valid:
return False
return True
grid = [[".",".",".","1","4",".",".","2","."],
[".",".","6",".",".",".",".",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".","1",".",".",".",".",".","."],
[".","6","7",".",".",".",".",".","9"],
[".",".",".",".",".",".","8","1","."],
[".","3",".",".",".",".",".",".","6"],
[".",".",".",".",".","7",".",".","."],
[".",".",".","5",".",".",".","7","."]]
grid2 = [[".",".",".",".","2",".",".","9","."],
[".",".",".",".","6",".",".",".","."],
["7","1",".",".","7","5",".",".","."],
[".","7",".",".",".",".",".",".","."],
[".",".",".",".","8","3",".",".","."],
[".",".","8",".",".","7",".","6","."],
[".",".",".",".",".","2",".",".","."],
[".","1",".","2",".",".",".",".","."],
[".","2",".",".","3",".",".",".","."]]
grid3 = [[".",".","4",".",".",".","6","3","."],
[".",".",".",".",".",".",".",".","."],
["5",".",".",".",".",".",".","9","."],
[".",".",".","5","6",".",".",".","."],
["4",".","3",".",".",".",".",".","1"],
[".",".",".","7",".",".",".",".","."],
[".",".",".","5",".",".",".",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".",".","."]]
grid4 = [[".","4",".",".",".",".",".",".","."],
[".",".","4",".",".",".",".",".","."],
[".",".",".","1",".",".","7",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".",".","3",".",".",".","6","."],
[".",".",".",".",".","6",".","9","."],
[".",".",".",".","1",".",".",".","."],
[".",".",".",".",".",".","2",".","."],
[".",".",".","8",".",".",".",".","."]]
print(sudoku2(grid))
print(sudoku2(grid2))
print(sudoku2(grid3))
print(sudoku2(grid4))