Ted Idzikowski - 5 months ago 28

Python Question

I already wrote one part of the program which is below:

`def matrix_is_square(matrix):`

for i in range(len(matrix)):

if len(matrix[i]) != len(matrix):

return False

return True

This function returns True if matrix is a square matrix, otherwise, it returns False.

HOWEVER, HERE'S WHEN THE PROBLEM BEGINS.

I Have to write a second function that determines if the function is Magic square.

A square matrix forms a magic square if the following conditions are met:

- The elements of the matrix are numbers 1,2,3,...,n
^{2} - The sum of the elements in each row, in each column and in the two diagonals is the same value

The code first begins with:

`def magic(matrix):`

if(not(is_square(matrix))):

return False

# The remaining code

This is what I attempted.

`square = []`

for i in range(len(matrix)):

square.append([])

for j in range(len(matrix)):

square[i].append(0)

total = 0

x = len(matrix)

for i in range(x):

total += square[i][i]

if total != x*(x*x+1)/2:

return False

else:

return True

total = 0;

for i in range(x):

total += square[i][x-1-i]

if total != x*(x*x+1)/2:

return False

else:

return True

There seem to be a couple of errors in my code. An important one is that I'm testing for exact equality of numbers, which is wrong because numbers cannot be represented exactly as floating points, but I can't find another way to do that. Any hints would be appreciated.

Here are the expected outcomes of this function just to be on the same page.

`[[2,7, 6],[9,5,1],[4,3,8]]`

`[[16,3,2,13], [5,10,11,8],[9,6,7,12], [4,15,14,1]]`

`[[1,2,3,4], [5,6,7,8],[9,10,11,12], [13,14,15,16]]`

`[[1,1],[1,1]]`

`[[1,1],[1,1],[1,2]]`

No import numpy.

Answer

Complex solution using `sum`

, `range`

, `any`

functions and `set`

object:

```
def magic(m):
length = len(m)
first_sum = set()
if length <= 2 \
or any(len(row) != length for row in m) \
or any(i > (length * length) for row in m for i in row):
return False
for r in m:
s = sum(r)
if len(first_sum) == 0:
first_sum.add(sum(r))
if s not in first_sum:
return False
for i in range(length):
s = sum([r[i] for r in m])
if s not in first_sum:
return False
if sum(m[i][i] for i in range(length)) not in first_sum \
or sum(m[i][i] for i in range(length - 1, -1, -1)) not in first_sum:
return False
return True
m = [[2,7,6],[9,5,1],[4,3,8]]
print(magic(m))
m = [[16,3,2,13], [5,10,11,8],[9,6,7,12], [4,15,14,1]]
print(magic(m))
m = [[1,2,3,4], [5,6,7,8],[9,10,11,12], [13,14,15,16]]
print(magic(m))
m = [[1,1],[1,1]]
print(magic(m))
m = [[1,1],[1,1],[1,2]]
print(magic(m))
```

The output(sequentially):

```
True
True
False
False
False
```