我是编码新手。我正在尝试编程一个魔术方块。幻方是一个正方形(在我的情况下是3×3,可能不同(,其中所有的行、列和对角线必须总和为某个数字(在我情况下是15,因为是3×4(。这是我的代码:
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
运算符。这样,只要任何条件为真(意味着任何一行加起来都不正确(,就可以保持循环。
或者,您可以保留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)