We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def formingMagicSquare(s):
# Write your code here
mincost=99
# a b c
# d e f
# g h i
for a in range(1,10):
if a==5:
continue
for b in range(1,10):
if b==5 or b==a:
continue
lst=[a,b]
cops=[[j for j in i] for i in s]
#calc a
calcCost=abs(a-cops[0][0])
cops[0][0]=a
#calc b
calcCost=calcCost + abs(b-cops[0][1])
cops[0][1]=b
#calc c
c=15-cops[0][0]-cops[0][1]
if c==5 or c<1 or c>9 or c in lst:
continue
calcCost=calcCost+abs(c-cops[0][2])
cops[0][2]=c
lst.append(c)
#calc d
d=5-cops[0][0]+cops[0][2]
if d==5 or d<1 or d>9 or d in lst:
continue
calcCost=calcCost+abs(d-cops[1][0])
cops[1][0]=d
lst.append(d)
#calc e
e=5
calcCost=calcCost+abs(e-cops[1][1])
cops[1][1]=e
#calc f
f=10-cops[1][0]
if f==5 or f<1 or f>9 or f in lst:
continue
calcCost=calcCost+abs(f-cops[1][2])
cops[1][2]=f
lst.append(f)
#calc g
g=10-cops[0][2]
if g==5 or g<1 or g>9 or g in lst:
continue
calcCost=calcCost+abs(g-cops[2][0])
cops[2][0]=g
lst.append(g)
#calc h
h=10-cops[0][1]
if h==5 or h<1 or h>9 or h in lst:
continue
calcCost=calcCost+abs(h-cops[2][1])
cops[2][1]=h
lst.append(h)
#calc i
i=10-cops[0][0]
if i==5 or i<1 or i>9 or i in lst:
continue
calcCost=calcCost+abs(i-cops[2][2])
cops[2][2]=i
lst.append(i)
if calcCost<mincost:
mincost=calcCost
print(mincost,cops)
return mincost
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Forming a Magic Square
You are viewing a single comment's thread. Return to all comments →
Python solution
def formingMagicSquare(s): # Write your code here mincost=99 # a b c # d e f # g h i