I'm coding a program that reads a line in a file and determines whether or not the line makes a Lo Shu Magic square. In this magic square, the sum of the rows, sum of the columns, and sum of the diagonals have to equal 15, and each number 1-9 can only occur once in the square. This is what I have so far:
def main():
for line in open("Magic Square Input.txt"):
items = line.split(" ")
items = [int(x) for x in items]
result = [items[0:3], items[3:6], items[6:9]]
isMagic(result)
def isMagic(result):
checks1 = ''
for x in result:
for y in range(3):
if sum (result[y][y] for y in range(3)) == 15:
if sum(x[y] for x in result) == 15:
checks1 = checkDupe(result)
else:
checks1 = 'Invalid'
else:
checks1 = 'Invalid'
print(checks1)
def checkDupe(result):
checks1 = ''
for i in range(0,8):
counter = 0
for j in result:
if (j == i):
counter += 1
if counter > 0:
checks1 = 'Invalid'
else:
checks1 = 'Valid'
return checks1
main()
the contents of my text file are as follows:
4 3 8 9 5 1 2 7 6
8 3 4 1 5 9 6 7 2
6 1 8 7 5 3 2 9 4
6 9 8 7 5 3 2 1 4
6 1 8 7 5 3 2 1 4
6 1 3 2 9 4 8 7 5
5 5 5 5 5 5 5 5 5
The first three numbers in each line represent the top row of the square, the next three are the middle row, and the last three are the bottom row. The problem im having is that the first three squares ARE valid, and the last four are supposed to be invalid. But what my code keeps printing out for me is
Valid
Valid
Valid
Valid
Valid
Invalid
Valid
Could somebody show me where I'm screwing up here? I'm fairly new to python and I've been staring at this for hours trying to make sense of it.
This problem is much easier to think about if you start with a flat list:
[4, 3, 8, 9, 5, 1, 2, 7, 6]
and then work out which indexes you need to check. There are only eight in all:
indexes = (
(0, 1, 2), (3, 4, 5), (6, 7, 8), # rows
(0, 3, 6), (1, 4, 7), (2, 5, 8), # cols
(0, 4, 8), (2, 4, 6), # diag
)
With that set up, the check function becomes very simple:
def main():
for line in open('Magic Square Input.txt'):
square = [int(n) for n in line.split()]
if len(set(square)) != len(square):
print('Invalid: Duplicates')
else:
for idx in indexes:
if sum(square[i] for i in idx) != 15:
print('Invalid: Sum')
break
else:
print('Valid')