我正在尝试制作一个返回布尔值的程序,无论矩阵是否为魔方。我尝试在我学院的网站上提交此代码,但它返回“错误答案”。我看不出它有什么问题。你能救我吗?
def magico(xs):
#print(soma(xs),soma2(xs),diag(xs))
if(soma(xs) == soma2(xs) == diag(xs) != -1 ):
return True
else:
return False
def soma(xs):
sant = 0
s = 0
for i in range(len(xs)):
if(s != sant):
return -1
s = 0
for j in range(len(xs)):
s = s + int(xs[i][j])
sant = s
return s
def soma2(xs):
s = 0
sant = 0
for j in range(len(xs)):
if(s != sant):
return -1
s = 0
for i in range(len(xs)):
s = s + int(xs[j][i])
sant = s
return s
def diag(xs):
s = 0
for i in range(len(xs)):
s = s + int(xs[i][i])
t = 0
for i in range(len(xs)):
t = t + int(xs[i][len(xs) - 1 - i])
if(s == t):
return s
else:
return -1
答案 0 :(得分:0)
伪代码
magic = true
answer = sum(square)/n_rows(square)
for r in rows(square):
if sum(r) not equal to answer
magic = false
for c in columns(square):
if sum(c) not equal to answer
magic = false
d1 = principal_diagonal(square)
d2 = secondary_diagonal(square)
if sum(d1) or sum(d2) not equal to answer
magic = false
display magic
答案 1 :(得分:0)
您没有检查矩阵是否为方形,您没有检查矩阵中的数字是否唯一。除此之外,您还有一个严重的编码问题: 你的循环都以
结尾sant = s
他们从
开始if(s != sant):
但你刚刚让他们平等......