我正在制作的程序是从文本文件中验证数独。到目前为止,我有这个。
file=input("Enter a filename: ")
with open(file) as data:
rowt=[0 for i in range(9)]
colt=[0 for i in range(9)]
for a,b in enumerate(data):
sb_rowt = 0
print (a,b)
for c, d in enumerate(b.split()):
print (c,d)
sb_rowt+=int(d)
colt[c]+=int(d)
rowt[a]=sb_rowt
rows=all(i==45 for i in rowt)
cols=all(i==45 for i in colt)
print(rows and cols)
这个问题是,如果我有一个像这样的文本文件
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5
程序仍将输出为true。我知道我需要删除任何重复的条目,但我不确定如何。
答案 0 :(得分:0)
通过你的提问,我认为你没有走上正轨。无论是否有效,电路板上应始终有9 * 9个数字。您获得了正确的输入,但无法验证它。 考虑改进验证算法。
答案 1 :(得分:0)
您应该将阅读和验证操作分开:
# read first
file = input("Enter a filename: ")
with open(file) as data:
array = [ [ int(i) for i in line.split() ] for line in data ]
然后才进行验证。
# first create a set of numbers 1...9
all_numbers = set(range(1, 10))
# validate rows and columns:
valid = True
# we validate ith row and column in the same loop
for i in range(9):
row_i = array[i]
column_i = [ array[rownum][i] for rownum in range(9) ]
valid &= set(row_i) == all_numbers
valid &= set(column_i) == all_numbers
# valid is True if all constraints succeeded.
# TODO: in sudoku you also need to validate the
# 3x3 subsquares.
答案 2 :(得分:0)
您不能只使用数字的总和来验证网格。相反,您必须检查每行和每列是否包含1到9之间的所有数字。
您可以尝试这样的事情:
all_nums = set(range(1, 10))
with open("data") as data:
field = [[int(x) for x in line.split()] for line in data]
rows = map(set, field)
cols = map(set, zip(*field))
rows_ok = all(row == all_nums) for row in rows)
cols_ok = all(col == all_nums) for col in cols)
首先,我从数据输入中创建一个整数列表。然后我提取行和列(zip(*field)
基本上翻转field
)并将它们转换为set
s,因为顺序并不重要。最后,我只是将all
行和列与all_nums
的集合进行比较。
答案 3 :(得分:0)
import csv
import collections
with open('path/to/file') as infile:
board = [[int(i) for i in row] for row in csv.reader(infile)]
for r,row in enumerate(board):
counts = collections.Counter(row)
if all(row[k]==1 for k in range(1,10)):
continue
raise ValueError("failed on row %d" %r)
for c,col in enumerate(zip(*rows)):
if all(col[k]==1 for k in range(1,10)):
continue
raise ValueError("failed on col %d" %c)
# todo: check each 3x3 square
答案 4 :(得分:0)
将您的董事会作为清单提供:
def validate(board):
valid = set(range(1, 10))
return (all(valid == set(r) for r in board) and
all(valid == set(c) for c in zip(*board)) and
all(valid == set(board[i][j:j+3] + board[i+1][j:j+3] + board[i+2][j:j+3])
for i in (0, 3, 6) for j in (0, 3, 6)))