【发布时间】:2018-11-18 22:36:38
【问题描述】:
我是编码新手。我正在尝试编写一个魔方。幻方是一个正方形(在我的情况下为 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 循环内部发生了什么。
【问题讨论】:
标签: python while-loop magic-square