Skip to content

Commit

Permalink
adding robust sudoku reader (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
iheitlager authored Nov 19, 2023
1 parent 3aa1054 commit 69f3233
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/sudoku/reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
def read_matrix(filename):
"""Read a matrix from a filename.
Note: wraps generic get_matrix method.
"""

with open(filename, "r") as f:
content = f.readlines()
return get_matrix(content)


def get_matrix(content):
"""Return a list of lists containing the content of text.
Note: each line of the text corresponds to a list. Each item in
the list is from splitting the line of text by the delimiter ' ' or ','.
Empty values are either 0 or . This is a fairly robust parser.
"""

if type(content) == str: # split textblob into list of lines
content = content.splitlines()

lines = []
for line in content:
new_line = line.strip() # Strip any leading or trailing whitespace
new_line = new_line.replace(".", "0") # dots are zero's
new_line = new_line.replace(",", "") # comma's are seperators
new_line = new_line.replace(" ", "") # spaces are seperators
if new_line:
new_line = [int(x) for x in new_line]
lines.append(new_line)

return lines
50 changes: 50 additions & 0 deletions tests/test_reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from sudoku import reader


example1 = """.......92
...1...4.
9..24...7
8..7..15.
65.9.1.78
.74..8..6
3...95..1
.8...6...
79.......
"""

example1_alt = """. . . .. ..92
...1...4.
9..2400.7
8..7..15.
6,5,.,9,.,1,.,7,8
.74..,8,.,.,6
3...95..1
.8...6...
790000000
"""

example1_list = [
[0,0,0,0,0,0,0,9,2],
[0,0,0,1,0,0,0,4,0],
[9,0,0,2,4,0,0,0,7],
[8,0,0,7,0,0,1,5,0],
[6,5,0,9,0,1,0,7,8],
[0,7,4,0,0,8,0,0,6],
[3,0,0,0,9,5,0,0,1],
[0,8,0,0,0,6,0,0,0],
[7,9,0,0,0,0,0,0,0]
]

def test_example():
m = reader.get_matrix(example1)
assert len(m) == 9
assert m[0] == [0,0,0,0,0,0,0,9,2]
assert m == example1_list

def test_example_alt():
m = reader.get_matrix(example1_alt)
assert m == example1_list

0 comments on commit 69f3233

Please sign in to comment.