Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Magic Square by TovarischZhukov
def check(data, nsum, i, j, val):
hor=data[i]; s1=sum(hor)
if 0 in hor: flag1 = s1< nsum
else: flag1 = s1 == nsum
ver=[]; verhor1=[]; verhor2=[]
for k in range(len(data)):
ver.append(data[k][j])
verhor1.append(data[k][k])
verhor2.append(data[k][-1-k])
s2=sum(ver)
if 0 in ver: flag2= s2 < nsum
else: flag2 = s2 == nsum
s3=sum(verhor1)
if 0 in verhor1: flag3 = s3 < nsum
else: flag3 = s3 == nsum
s4=sum(verhor2)
if 0 in verhor2: flag4 = s4 < nsum
else: flag4 = s4 == nsum
return flag1 and flag2 and flag3 and flag4
def find(data, numbers, nsum):
if not numbers: return data
number=numbers[0]
numbers=numbers[1:]
for i in range(len(data)):
for j in range(len(data)):
if not data[i][j]:
n_data= data[:]
n_data[i]=data[i][:]
n_data[i][j]=number
if check(n_data, nsum, i, j, number):
r=find(n_data, numbers, nsum)
if r: return r
def checkio(data):
numbers=set(range(1,len(data)**2+1)).difference(val for el in data for val in el)
nsum=len(data)*(len(data)**2+1)/2
r = find(data,list(numbers),nsum)
if not r:
r=[]
for i in range(len(data)):
a.append([])
for j in range(len(data)):
r[-1].append(0)
return r
Feb. 15, 2016