From 69f3233d905b0a9af797054d4dbf87c544fc7d58 Mon Sep 17 00:00:00 2001 From: Ilja Heitlager Date: Sun, 19 Nov 2023 18:37:59 +0100 Subject: [PATCH] adding robust sudoku reader (#29) --- src/sudoku/reader.py | 33 +++++++++++++++++++++++++++++ tests/test_reader.py | 50 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 src/sudoku/reader.py create mode 100644 tests/test_reader.py diff --git a/src/sudoku/reader.py b/src/sudoku/reader.py new file mode 100644 index 0000000..0ae4a5a --- /dev/null +++ b/src/sudoku/reader.py @@ -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 diff --git a/tests/test_reader.py b/tests/test_reader.py new file mode 100644 index 0000000..6684309 --- /dev/null +++ b/tests/test_reader.py @@ -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 \ No newline at end of file