For my programming class, we have been tasked with creating a Sudoku solver; the first step of the project was to create a program which would display the game board based on input provided by the user.
import math #To be used later
def board_filler():
"""Creates the sudoku board from user input"""
board = [[], [], [], [], [], [], [], [], [], [], []]
for x in enumerate(board):
#If it is one of the rows that have lines, add them
if ((x[0] + 1) % 4) == 0:
for y in range(11):
board[x[0]].append("-")
else:
for y in range(11):
#If it is a column that has lines in it, add them
if ((y + 1) % 4) == 0:
board[x[0]].append("|")
else:
#Repeat until an inout has been entered
z = True
while z:
z = False
if x[0] > 7:
xRead = x[0] - 1
elif x[0] > 3:
xRead = x[0]
else:
xRead = x[0] + 1
if y > 7:
yRead = y - 1
elif y > 3:
yRead = y
else:
yRead = y + 1
number = input("Please enter a number for the square in column %s and in row %s, if there is no number, just hit enter:" %(xRead, yRead))
#Trys to make it a number, then checks to see if it is a number 1 to 9
try:
number = int(number)
if number > 9 or number < 1:
z = True
print("Please enter a number between 1 and 9")
else:
board[x[0]].append(number)
#If it is not a number, check if its empty
except (TypeError, ValueError):
#If its empty, add a space
if len(number) == 0:
board[x[0]].append(" ")
#If not ask for a number
else:
z = True
print("Please enter a number")
return board
def board_printer(board):
"""Prints the sudoku board"""
#Turns board into str to make the .join work
for x in enumerate(board):
for y in enumerate(board):
board[x[0]][y[0]] = str(board[x[0]][y[0]])
#Prints the board
for x in enumerate(board):
print(" ".join(board[x[0]]))
board_printer(board_filler())
A few notes for review:
- The
board_filler
function feels quite bloated. - I don't like the way I implemented
xRead
andyRead
.
How can I improve my code?
Enter
80 times \$\endgroup\$xRead
andyRead
? \$\endgroup\$