0

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()
solo fisher
  • 65
  • 2
  • 10
  • Someone (It seems that he's a classmate) asked the same question few hours earlier, try to check this thread :: http://stackoverflow.com/questions/26457089/magic-square-algorithm – user3378649 Oct 20 '14 at 03:02
  • Does rowNum refer to the amount of rows in the matrix? – Totem Oct 20 '14 at 03:19
  • he wrote this rowSum(matrix, rowNum) : return sum of the specified row of matrix – solo fisher Oct 20 '14 at 03:25
  • possible duplicate of [TypeError: 'int' object is not subscriptable Python read file](http://stackoverflow.com/questions/26498856/typeerror-int-object-is-not-subscriptable-python-read-file) – Paul Oct 22 '14 at 01:46

3 Answers3

1

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()
Totem
  • 7,189
  • 5
  • 39
  • 66
  • ok thanks that seems to work. To calculate the column sums i would do the same as rowSum but instead of for i in matrix([rowNum]) it would be for j in matrix([colNum])? – solo fisher Oct 20 '14 at 03:50
  • I included the same code again, but this time it sums the column of choice. – Totem Oct 20 '14 at 04:02
1

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!

JamesENL
  • 6,400
  • 6
  • 39
  • 64
jcabrera
  • 136
  • 5
  • i dont think he wanted to enter a row because this is for a magic square program. Im suppose to see if the sums of each row, column and two diagnols are the same – solo fisher Oct 21 '14 at 02:25
  • In that case you can modify the above code to also keep track of columns, since they are already in lists, and iterate any way you want through it. But by giving the row number it gets a specific functionality, which can actually be ported to columns and so forth, and use those methods as the basis for a full check on all sums, with the advantage of being modular and easy to change the behavior when needed (Or analyze it). From there you can make colSum(matrix, rowNum), you can even make them also check for the sums of their respective diagonals. Or clarify with him why not do it in one step. – jcabrera Oct 21 '14 at 03:57
0

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
Dyue
  • 1
  • 1