Skip to content

Instantly share code, notes, and snippets.

@pvleite
Created July 5, 2014 00:03
Show Gist options
  • Save pvleite/7d7fe35b0073a9c85fa1 to your computer and use it in GitHub Desktop.
Save pvleite/7d7fe35b0073a9c85fa1 to your computer and use it in GitHub Desktop.
Check if a list of lists (A x A) is a "magic square", in other words, if the sum of all values in all rows, columns and diagonals has the same value
def validaQMagico(QMagico):
if len(QMagico) == 0 or len(QMagico) != len(QMagico[0]): return False
linhasOK = not sum([ True if sum(linha) != sum(QMagico[0]) else False for linha in QMagico ])
colunasOK = not sum([ sum([ linha[i] for linha in QMagico ]) != sum(QMagico[0]) for i in range(len(QMagico[0])) ])
diagonaisOK = True
for i in range(len(QMagico[0])):
if (sum( [linha[i] for linha in QMagico] )!=sum(QMagico[0])): diagonaisOK = False
i+=1
return linhasOK and colunasOK and diagonaisOK
QMagico = [ [2, 7, 6], [9, 5, 1], [4, 3, 8] ]
print(QMagico, validaQMagico(QMagico))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment