0

I am trying to create a program that opens a text file containing a magic square, which is laid out like this: (I have updated the code now. There is no longer a debug error however the program doesn't actually function)

1 2 3
4 5 6
7 8 9

I have run into millions of problems with importing the contents of the txt file into the program, for example the text file seemed to be imported as lists containing strings.

I'm not sure what I'm doing wrong or if my whole code is wrong. Please bear in mind that I am very rusty with Python and it has been at least a year since I had to program anything advanced. Thank you (My entire code is listed below)

print("Welcome to the Magic Square puzzle validation program.")
file = input("Please input the name of the file you would like to open: ")
    
with open(file) as data_file:
    for line in data_file:
        data = line.split()
        data = [list(map(int, data))]
        print(data)
        

isSquare = False
n = len(data)
diagLeft=0
diagRight=0

for i in range(n):
    diagLeft+=data[i][i]
    diagRight+=data[i][n-i-1]

if not(diagLeft==diagRight):
    isSquare == False
for i in range(n):
    rows=0
    columns=0
for j in range(n):
      rows+=data[i][j]
      columns+=data[j][i]

if not(rows==columns==diagLeft):
    isSquare == False
else:
    isSquare == True
     
       
if isSquare == True :
    print("Your Magic Square is valid!")
else :
    print("Your Magic Square is invalid!")

jotachin
  • 15
  • 5
  • 1
    In your code `data` is a single row, but you are trying to treat it as a 2-dimensional array. – John Coleman Mar 22 '22 at 09:57
  • 1
    You are treating data as a 2D array, but it is not. From `data = line.split()` it is obvious that it will contain the last row of the input file only. Now think how that relates to your `TypeError: 'int' object is not subscriptable`. – mcsoini Mar 22 '22 at 09:58
  • Thank you! Is there a way to convert a list to an array without using numPy? All the information I seem to have found uses the numPy library which I cannot use in this instance. – jotachin Mar 22 '22 at 10:01
  • 1
    An array is a numpy object. What you could do if you want a similar data format is use a list of lists but then you do not have the shape information that is given with an array (i.e. you have to loop through your list of lists and check each list's length to determine the number of clumns). – Harpe Mar 22 '22 at 10:06

0 Answers0