Poem Decoder
This script takes a text file and decodes it as a Sudoku puzzle as described in this poem.
#!/usr/bin/env python3
import sys
import string
from itertools import batched
def main():
filename = sys.argv[1]
with open(filename, encoding="utf-8") as f:
text = f.read()
text = text.translate(str.maketrans("", "", string.punctuation))
words = text.split()
triplets = list(batched(words, 3))
if len(words) % 3 == 0:
for triplet in triplets:
lengths = ", ".join(str(len(word)) for word in triplet)
print(f"{' '.join(triplet)} : {lengths}")
for triplet in triplets:
lengths = ", ".join(str(len(word)) for word in triplet)
print(f"{lengths}")
grid = [[0] * 9 for _ in range(9)]
for triplet in triplets:
row, col, value = (len(word) for word in triplet)
if not all(1 <= n <= 9 for n in (row, col, value)):
print(f"{row}, {col}: {val}")
exit()
if grid[row - 1][col - 1] not in (0, value):
raise SystemExit(f"conflict at {row},{col}")
grid[row - 1][
col - 1
] = value # rows and columns are 1-9; Python lists start at 0
print_sudoku(grid)
def print_sudoku(grid):
for r, row in enumerate(grid):
if r % 3 == 0 and r > 0:
print("------+-------+------")
cells = [str(v) if v else "." for v in row]
print(" | ".join(" ".join(cells[c : c + 3]) for c in (0, 3, 6)))
if __name__ == "__main__":
main()poem_to_sudoku_decoder.py