python - 幻方 python

标签 python magic-square

我正在编写一个程序,该程序读取文件中的一行并确定该行是否构成 Lo Shu 幻方。在这个魔方中,行的和、列的和、对角线的和必须等于 15,并且每个数字 1-9 在方 block 中只能出现一次。这是我目前所拥有的:

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

每行的前三个数字代表正方形的顶行,接下来的三个是中间行,最后三个是底行。我遇到的问题是前三个方 block 是有效的,而后四个方 block 应该是无效的。但是我的代码不断为我打印的是

Valid
Valid
Valid
Valid
Valid
Invalid
Valid

有人可以告诉我哪里搞砸了吗?我是 python 的新手,我已经盯着它看了好几个小时试图理解它。

最佳答案

如果从平面列表开始,这个问题会更容易思考:

[4, 3, 8, 9, 5, 1, 2, 7, 6]

然后计算出您需要检查哪些索引。总共只有八个:

indexes = (
    (0, 1, 2), (3, 4, 5), (6, 7, 8), # rows
    (0, 3, 6), (1, 4, 7), (2, 5, 8), # cols
    (0, 4, 8), (2, 4, 6),            # diag
    )

有了这个设置,检查功能变得非常简单:

def main():
    for line in open('Magic Square Input.txt'):
        square = [int(n) for n in line.split()]
        if len(set(square)) != len(square):
            print('Invalid: Duplicates')
        else:
            for idx in indexes:
                if sum(square[i] for i in idx) != 15:
                    print('Invalid: Sum')
                    break
            else:
                print('Valid')

关于python - 幻方 python ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42056379/

相关文章:

python - pip 安装私有(private)包

python - 在numpy中的一个函数中计算均值或中值

序言 我必须编写一个程序来计算魔法矩阵排列

java - 是否可以将我的代码压缩成少于 3 行?

java - Magic Square 给出 ArrayIndexOutOfBoundException

java - Magic Square 程序帮助 (Java)

python - Pygame:收到一个错误,表明 Sprite 是不可迭代的

python - 将 UUID 编号列表保存到 python 中的 .csv 文件

python - 在 numpy 对象数组中搜索

java - 求解单偶幻方 (Lux)