【发布时间】:2017-02-05 19:37:29
【问题描述】:
我正在编写一个程序,它读取文件中的一行并确定该行是否构成 Lo Shu 魔方。在这个幻方中,行之和、列之和、对角线之和必须等于 15,并且每个数字 1-9 在正方形中只能出现一次。这是我目前所拥有的:
def main():
for line in open("Magic Square Input.txt"):
items = line.split(" ")
items = [int(x) for x in items]
result = [items[0:3], items[3:6], items[6:9]]
isMagic(result)
def isMagic(result):
checks1 = ''
for x in result:
for y in range(3):
if sum (result[y][y] for y in range(3)) == 15:
if sum(x[y] for x in result) == 15:
checks1 = checkDupe(result)
else:
checks1 = 'Invalid'
else:
checks1 = 'Invalid'
print(checks1)
def checkDupe(result):
checks1 = ''
for i in range(0,8):
counter = 0
for j in result:
if (j == i):
counter += 1
if counter > 0:
checks1 = 'Invalid'
else:
checks1 = 'Valid'
return checks1
main()
我的文本文件内容如下:
4 3 8 9 5 1 2 7 6
8 3 4 1 5 9 6 7 2
6 1 8 7 5 3 2 9 4
6 9 8 7 5 3 2 1 4
6 1 8 7 5 3 2 1 4
6 1 3 2 9 4 8 7 5
5 5 5 5 5 5 5 5 5
每行的前三个数字代表正方形的顶行,接下来的三个是中间行,最后三个是底行。我遇到的问题是前三个方块是有效的,而后四个应该是无效的。但是我的代码不断为我打印出来的是
Valid
Valid
Valid
Valid
Valid
Invalid
Valid
谁能告诉我我在哪里搞砸了?我对 python 还很陌生,我一直盯着这个几个小时试图理解它。
【问题讨论】:
-
可能首先只检查行,然后只检查列,最后是对角线——这样更容易控制。而且不用拆分成行会更容易——行:
sum(items[0:3]),列:sum([items[0], items[3], items[6]]),对角线:sum([items[0], items[4], items[8]]) -
你可以使用
len(set(items)) = 9检查数字是否不重复 -
或者您可以检查数字 1-9 是否为
items-for x in range(1, 10): if x not in items: Invalid -
顺便说一句:你检查数字 0-7,而不是 1-9。
-
如果您有问题,请使用多个
print()来检查变量中的值以及执行了哪部分代码 - 这有助于发现问题。
标签: python magic-square