Forming a Magic Square

Photo by Katrina Wright on Unsplash
def formingMagicSquare(s):
s1 = [j for sub in s for j in sub] #Step-1 #flating the 2-d list to 1-d list
magic=[[8, 1, 6, 3, 5, 7, 4, 9, 2], #genearted this by another program
[6, 1, 8, 7, 5, 3, 2, 9, 4],
[4, 9, 2, 3, 5, 7, 8, 1, 6],
[2, 9, 4, 7, 5, 3, 6, 1, 8],
[8, 3, 4, 1, 5, 9, 6, 7, 2],
[4, 3, 8, 9, 5, 1, 2, 7, 6],
[6, 7, 2, 1, 5, 9, 8, 3, 4],
[2, 7, 6, 9, 5, 1, 4, 3, 8]]
#minimumcost=1000
minimum_cost=sys.maxsize Step-2#setting up a max value can be any max val
for mag in magic: Step-3#iterate through the magic list
diff=0
for i,j in zip(s1,mag): #Step-4#we zip s1,mag to perform sub operation to calculate the diff
diff+=abs(i-j)
print("difference in iteration-",diff)
print("Max-",minimum_cost)
minimumcost=min(minimum_cost,diff) #Step-5 #keep on updating minimum_cost value as in 1st iteration it will be max value
return minimum_cost
for i,j in zip(s1,mag):
diff+=abs(i-j)
minimumcost=min(minimum_cost,diff)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store