Python 不应该';这段代码是否为3*3幻方的所有9个变量生成了一个可满足的值?
在核心2二人组比赛中花了22分钟,没有结果Python 不应该';这段代码是否为3*3幻方的所有9个变量生成了一个可满足的值?,python,python-3.x,Python,Python 3.x,在核心2二人组比赛中花了22分钟,没有结果 for a in range(10): for b in range(10): while b!=a: for c in range(10): while c!= a or b: for d in range(10): while d!=a or b or c:
for a in range(10):
for b in range(10):
while b!=a:
for c in range(10):
while c!= a or b:
for d in range(10):
while d!=a or b or c:
for e in range(10):
while e!=a or b or c or d:
for f in range(10):
while f!=a or b or c or d or e:
for g in range(10):
while g!=a or b or c or d or e or f:
for h in range(10):
while h!= a or b or c or d or e or f or g:
for i in range(10):
while i!= a or b or c or d or e or f or g or h:
if (a+b+c==15 and a+d+g==15 and d+e+f==15 and g+h+i==15 and b+e+h==15 and c+f+i==15 and a+e+i==15 and c+e+g==15):
print(a,b,c,d,e,f,g,h,i)
这很难看,但错误在于你不能像这样进行比较
while e!=a or b or c or d:
相反,你应该写作
while e!=a and e!=b and e!=c and e!=d:
请学习如何使用数组/列表并重新思考问题。@Selcuk已识别出您的问题;以下是一种改进的方法:
# !!! Comments are good !!!
# Generate a magic square like
#
# a b c
# d e f
# g h i
#
# where each row, col, and diag adds to 15
values = list(range(10)) # problem domain
unused = set(values) # compare against a set
# instead of chained "a != b and a != c"
SUM = 15
for a in values:
unused.remove(a)
for b in values:
if b in unused:
unused.remove(b)
# value for c is forced by values of a and b
c = SUM - a - b
if c in unused:
unused.remove(c)
#
# etc
#
unused.add(c)
unused.add(b)
unused.add(a)
这会起作用,但仍然很难看
从长远来看,最好使用约束解算器,如:
请注意,这将返回8个解决方案,它们都是彼此的旋转和镜像版本。如果只需要唯一的解决方案,可以添加一个约束,如
prob.addConstraint(lambda a,c,g: a<c<g, "acg")
prob.addConstraint(lambda a,c,g:aplese-see。哇,这很难看。这有O(sh*t)复杂度。哇,这也很难看。如果条件为真,所有那些while
循环将无限运行。此外,你误用了或。你不是指范围(1,10)
?这甚至不应该是一个,而循环,它只是无限循环。
prob.addConstraint(lambda a,c,g: a<c<g, "acg")
values = set(range(1, 10))
SUM = 15
for a in values:
for c in values:
if a < c: # for unique ordering
for g in values:
if c < g: # for unique ordering
b = SUM - a - c
d = SUM - a - g
e = SUM - c - g
f = SUM - d - e
h = SUM - b - e
i = SUM - a - e
if {a,b,c,d,e,f,g,h,i} == values:
print(
"{} {} {}\n{} {} {}\n{} {} {}\n\n"
.format(a,b,c,d,e,f,g,h,i)
)