CarlosLabs
Hackerrank Challenges - Forming a magic square
{CM} I read a little about the
topology of magic squares
before jumping onto it
#!/bin/python3 import math import os import random import re import sys # Complete the formingMagicSquare function below. def formingMagicSquare(s): wkSqr = s candidates = [ [[4,9,2],[3,5,7],[8,1,6]], [[2,7,6],[9,5,1],[4,3,8]], [[6,1,8],[7,5,3],[2,9,4]], [[8,3,4],[1,5,9],[6,7,2]], [[2,9,4],[7,5,3],[6,1,8]], [[6,7,2],[1,5,9],[8,3,4]], [[8,1,6],[3,5,7],[4,9,2]], [[4,3,8],[9,5,1],[2,7,6]] ] totals = [] for p in candidates: total = 0 for p_row, s_row in zip(p, s): for i, j in zip(p_row, s_row): if not i == j: total += max([i, j]) - min([i, j]) totals.append(total) return min(totals) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = [] for _ in range(3): s.append(list(map(int, input().rstrip().split()))) result = formingMagicSquare(s) fptr.write(str(result) + '\n') fptr.close()