python 中的幻方

Magic square in python

我是编码新手。我正在尝试编写一个幻方。幻方是一个正方形(对于我的情况是 3 × 3,可能不同),其中所有行和列以及对角线的总和必须等于某个数字(对于我的情况是 15,因为 3 × 3)。这是我的代码:

s = []
while len(s) < 9:
    n = 0
    a = random.randrange(1, 10)
    while a not in s:
        s.append(a)


while s[0] + s[1] + s[2] != 15 and s[3] + s[4] + s[5] != 15 and \
        s[6] + s[7] + s[8] != 15 and s[0] + s[4] + s[8] != 15 \
        and s[2] + s[4] + s[6] != 15 and s[0] + s[3] + s[6] != 15 and \
        s[1] + s[4] + s[7] != 15 and s[2] + s[5] + s[8] != 15:
    shuffle(s)
print(s)

我不明白为什么程序在 while 循环中满足所有条件之前不洗牌。我知道这不是编写此程序的方法,即使它可以工作,也将是随机性和暴力强制解决方案,我只想了解 while 循环内发生的事情。

我认为你写错了循环条件。目前要求行、列或对角线的 none 相加为正确的值。如果它们中的任何一个这样做,它就会退出,因为链式 and 会产生 False 值。

相反,我认为您想使用 or 运算符而不是 and 运算符。这样,只要 any 条件为真(意味着任何行都没有正确加起来),您就会继续循环。

或者,您可以保留 and 运算符,但将 != 运算符更改为 == 并在最后否定整个事情(因为 not X or not Y 是逻辑上等同于 not (X and Y)):

while not (s[0] + s[1] + s[2] == 15 and s[3] + s[4] + s[5] == 15 and 
           s[6] + s[7] + s[8] == 15 and s[0] + s[4] + s[8] == 15 and
           s[2] + s[4] + s[6] == 15 and s[0] + s[3] + s[6] == 15 and
           s[1] + s[4] + s[7] == 15 and s[2] + s[5] + s[8] == 15):

我想你的意思是用 'ors' 替换你的 'ands'。一旦满足第一个条件,程序就会终止,因为从逻辑上讲,您编写它的方式需要满足所有这些条件才能继续。此外,虽然不是绝对必要,但我通常发现围绕单个逻辑条件的括号往往会有所帮助。

s = []
while len(s) < 9:
    n = 0
    a = random.randrange(1, 10)
    while a not in s:
        s.append(a)


while (s[0] + s[1] + s[2] != 15) or (s[3] + s[4] + s[5] != 15) or \
    (s[6] + s[7] + s[8] != 15) or (s[0] + s[4] + s[8] != 15) \
    or (s[2] + s[4] + s[6] != 15) or (s[0] + s[3] + s[6] != 15) or \
    (s[1] + s[4] + s[7] != 15) or (s[2] + s[5] + s[8] != 15):
    shuffle(s)
print(s)