0

This is a magic square program that can find out if any size matrix is a magic square. When i run the code i get error TypeError: 'int' object is not subscriptable. I decided to change line = int(i) to line = i but that just gave me another error. Cant use numpy

EDIT: Now i get this error TypeError: 'int' object is not iterable

text file:

1 1
6 8

Here is code:

def main():
    filNam = "matrix8.txt"
    matrix = (readMatrix(filNam))
    rowNum = 0
    colNum = 0
    print(rowSum(matrix, rowNum))

def readMatrix(filNam):
    matrixList = []
    numFile = open(filNam, "r")
    lines = numFile.readlines()
    for line in lines:
        line = line.split()
        row = []
        for i in line:
            row.append(int(i))
        matrixList.append(row)
    return matrixList

def eachNumPresent(matrix):
    if len(matrix) % 2 != 0:
        return False
    else:
        return True

def rowSum(matrix, rowNum):
    for row in matrix[rowNum]:
        row = sum(int(row))
        rowNum = rowNum + 1
    return i


def colSum(matrix):
    length = len(matrix)
    col_rows = 0
    for i in range(length):
        col_rows = col_rows + matrix[i][0]
        return col_rows

main()
0

1 Answer 1

1

The problem is that the matrix gets "flatten" into one long row. In order to fix it you should read & construct the matrix row-by-row.

Change:

def readMatrix(filNam):
    matrixList = []
    numFile = open(filNam, "r")
    lines = numFile.readlines()
    for line in lines:
        line = line.split()
        for i in line:
            line = int(i)
            matrixList.append(line)
    return matrixList

to:

def readMatrix(filNam):
    matrixList = []
    numFile = open(filNam, "r")
    lines = numFile.readlines()
    for line in lines:
        line = line.split()
        row = []  # 1st change
        for i in line:
            row.append(int(i)) # 2nd change
        matrixList.append(row) #3rd change
    return matrixList

changing the code and running it on the input provided in the question it prints 2 which is the sum of the first row in the matrix.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.