Created
April 27, 2019 22:25
-
-
Save newsch/6de73421e7bfce8b307344b10e0f9945 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Format a csv-styled 9x9 sudoku board. | |
Usage: `sudoku -g -fcsv | ./receipt-sudoku.py - > receipt.txt | |
""" | |
from typing import List | |
SudokuBoard = List[List[int]] | |
def parse_csv(text: str) -> SudokuBoard: | |
"""Parse a csv file of sudoku values.""" | |
board = [] | |
for line in text.splitlines(keepends=False): | |
row = list(map(lambda a: ' ' if a=='' else a, line.split(","))) | |
assert len(row) == 9 | |
board.append(row) | |
assert len(board) == 9 | |
return board | |
def format_sudoku(board: SudokuBoard) -> str: | |
# https://stackoverflow.com/questions/37952851/formating-sudoku-grids-python-3 | |
outs = [] | |
outs.append("+" + "---+"*9) | |
for i, row in enumerate(board): | |
outs.append(("|" + " {} {} {} |"*3).format(*[x if x != 0 else " " for x in row])) | |
if i % 3 == 2: | |
outs.append("+" + "---+"*9) | |
else: | |
outs.append("+" + " +"*9) | |
return "\n".join(outs) | |
def pad_string(string: str, padding: int) -> str: | |
return "".join((" " * padding + line for line in string.splitlines(keepends=True))) | |
if __name__ == "__main__": | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument("csvfile", type=argparse.FileType("r")) | |
args = parser.parse_args() | |
print(pad_string(format_sudoku(parse_csv(args.csvfile.read())), 5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment