简体   繁体   中英

Python reading matrix from file

This is for my IT class, i am trying to find the sum of each row. Its a magic square program. when i run this it says int object not iterable. Also the teacher wants the header of the function like this def rowSum(matrix, rowNum) but i dont understand why rowNum would be needed. The function should be able to calculate the sum of each row of any size matrix. Also i cant use numpy and enumarate as we have not talked about it in class yet.

Matrix txt file:

1 4
3 2 

Here is code

def main():
    filNam = "matrix1.txt"
    matrix = (readMatrix(filNam))
    print(eachNumPresent(matrix))
    print(rowSum(matrix))

def readMatrix(filNam):
    matrixFile = open(filNam, "r")
    line = matrixFile.readline()
    for line in matrixFile:
        line = line.split()
    return line
    matrixFile.close()

def eachNumPresent(matrix):
    if len(matrix) % 2 == 0:
        return True
    else:
        print("Not enough numbers")

def rowSum(matrix, rowNum):
    for line in matrix:
        return(sum(int(line)))

main()

How about this, it assumes that when you want the first row, you type '0' if you wanted the second row you would type '1' and so on ... easily changed.

def main():
    fn = "matrix1.txt"
    matrix = readMatrix(fn)
    n = int(input("Enter row number: "))
    rowSum(matrix, n)

def readMatrix(fn):
    matrix = []
    with open(fn) as f: # a with block will auto close your file after the statements within it
        for line in f:
            line = line.strip() # strip off any trailing whitespace(including '\n')
            matrix.append(line.split()) 
    return matrix

def rowSum(matrix, rowNum):
    result = sum(int(i) for i in matrix[rowNum])
    print("The sum of row {} = {}".format(rowNum, result))

main()

Example output:

The sum of row 1 = 5

EDIT:

To calculate the sum of a column:

def main():
    fn = "matrix1.txt"
    matrix = readMatrix(fn)
    n = int(input("Enter col number: "))
    colSum(matrix, n)

def readMatrix(fn):
    matrix = []
    with open(fn) as f: # a with block will auto close your file after the statements within it
        for line in f:
            line = line.strip() # strip off any trailing whitespace(including '\n')
            matrix.append(line.split()) 
    return matrix

def colSum(matrix, colNum):
    result = sum(int(row[colNum]) for row in matrix)
    print("The sum of col {} = {}".format(colNum, result))

main()

You weren't iterating over the correct sequence, you used "readline" instead of "readlines", which read only one of the lines of the matrix, not the full file. What you wanted to do was read all lines, and convert those lines to lists, so you could use sum() on it. Notice how after the split you need to make sure you convert the resulting strings to int. With that you form the matrix as a list of lists (in the format [[1,2],[3,4]]), and you can then pass the row number (starting at zero, but can be adjusted) to the rowSum method (That's why your teacher gave you that format for it)

See the differences in the corrected example (I laid out the steps for the conversion for example in different operations, but you can actually refactor that code to get it done in less lines):

def main():
    filNam = "matrix1.txt"
    matrix = (readMatrix(filNam))
    print(eachNumPresent(matrix))
    print(rowSum(matrix, 0))

def readMatrix(filNam):
    with open(filNam, 'r') as matrixFile:
        matrix = []
        lines = matrixFile.readlines()
        for line in lines:
            items = line.split()
            numbers = [int(item) for item in items]
            print numbers
            matrix.append(numbers)
        return matrix

def eachNumPresent(matrix):
    if len(matrix) % 2 == 0:
        return True
    else:
        print("Not enough numbers")

def rowSum(matrix, rowNum):
    for line in matrix:
        return(sum(line))

main()

If you need any clarification just let me know... Hope it helps!

1.you can learn pandas

2.your code has error, here is my code

def main():
    filNam = "matrix1.txt"
    rowNum, matrix = (readMatrix(filNam))
    print(eachNumPresent(rowNum))
    rowSum(matrix)

def readMatrix(filNam):
    matrix_list = []
    total_num = 0
    with open(filNam, 'r') as matrixFile:
        for line in matrixFile.readlines():
            line = line.split()
            line = [int(i) for i in line]
            matrix_list.append(line)
            total_num += len(line)
    return total_num, matrix_list

def eachNumPresent(num):
    if num % 2 == 0:
        return True
    else:
        print("Not enough numbers")

def rowSum(matrix):
    for row in matrix:
        print sum(row)

main()

out:

True
5
5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM