Python罗舒魔术

时间:2017-03-14 05:57:17

标签: python

我正在尝试测试一个Lo Shu Magic Square功能,但我遇到了一些问题。其中一个问题是我收到一条错误消息,上面写着TypeError:' int'对象不可迭代,但我看不出我做错了什么。其次是有更好的更有效的方法来编写这个代码来检查lo_shu_square变量是否是一个Lo Shu Magic Square?我是Python的新手,但它似乎效率低下。

ROWS = 3
COLUMNS = 3

def magic():
    lo_shu_square = [[8, 1, 6],[3, 5, 7],[4, 9, 2]]
    for r in range (ROWS):
        for c in range (COLUMNS):
            if sum(r) == sum (lo_shu_square[c][c] for c in range(COLUMNS)):
                if sum(r)== sum(r[c] for r in lo_shu_square):
                    answer_output = str('a Lo Shu Magic Square')
            else:
                answer_output = str('not a Lo Shu Magic Square')

    print("The inputs are", answer_output)

magic()

错误消息:

if sum(r) == sum (lo_shu_square[c][c] for c in range(COLUMNS)):
TypeError: 'int' object is not iterable

1 个答案:

答案 0 :(得分:-2)

谢谢@Arman!这是一个简单的解决方案。

COLUMNS = 3

def magic():
    lo_shu_square = [[8, 1, 6],[3, 5, 7],[4, 9, 2]]
    for r in lo_shu_square:
        for c in range (COLUMNS):
            if sum(r) == sum (lo_shu_square[c][c] for c in range(COLUMNS)):
                if sum(r)== sum(r[c] for r in lo_shu_square):
                    answer_output = str('a Lo Shu Magic Square')
            else:
                answer_output = str('not a Lo Shu Magic Square')

    print("The inputs are", answer_output)

magic()