Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
17-liner: clean solution in Clear category for Magic Square by przemyslaw.daniel
def checkio(data):
from itertools import product
size, value = len(data), (len(data)**2+1)*len(data)//2
stack = [(data, set(range(1, size**2+1))-{x for y in data for x in y})]
while stack:
data, numbers = stack.pop()
if any([sum(x) != value and not x.count(0) for x in data]) or \
any([sum(x) != value and not x.count(0) for x in zip(*data[::-1])]):
continue
if not len(numbers) and sum([data[x][x] for x in range(size)]) == value and \
sum([data[size-x-1][x] for x in range(size)]) == value:
return data
x, y = next(((i, j) for i, j in product(range(size), range(size))
if data[i][j] == 0), (-1, -1))
for v in list(numbers)*((x, y) != (-1, -1)):
data[x][y] = v
stack += [([list(i) for i in data], numbers-{v})]
March 29, 2017
Comments: