Python魔方

2024-04-25 09:16:28 发布

您现在位置: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循环内发生了什么。在


Tags: and代码in程序编码lennotrandom
2条回答

我想你的意思是把你的“AND”换成“ors”。只要满足第一个条件,程序就会立即终止,因为从逻辑上讲,所有这些条件都必须满足才能继续运行。另外,虽然不是严格必要的,但我通常发现在单个逻辑条件周围加括号往往会有所帮助。在

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)

我想你把循环的条件写错了。它目前要求行、列或对角线的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):

相关问题 更多 >