0
votes

I am new to Python programming. I have this assignment:

For this lab, you will work with two-dimensional lists in Python. Do the following:

  1. Write a function that returns the sum of all the elements in a specified column in a matrix using the following header def sumColumn(matrix, columnIndex)
  2. Write a function that displays the elements in a matrix row by row, where the values in each row are displayed on a separate line (see the output below). The format of your output must match that in the sample output where the values on a row are separated by a single space.

  3. Write a test program (i.e., a main function) that reads a 3 X 4 matrix and displays the sum of each column. The sum should be formatted to contain exactly one significant digit after the decimal point. The input from the user must be entered as in the sample program run below where the input is read row by row and values in a row are separated by single space.

Sample program run is as follows:

Enter a 3-by-4 matrix row for row 0: 2.5 3 4 1.5 Enter a 3-by-4 matrix row for row 1: 1.5 4 2 7.5 Enter a 3-by-4 matrix row for row 2: 3.5 1 1 2.5

The matrix is 2.5 3.0 4.0 1.5 1.5 4.0 2.0 7.5 3.5 1.0 1.0 2.5

Sum of elements for column 0 is 7.5 Sum of elements for column 1 is 8.0 Sum of elements for column 2 is 7.0 Sum of elements for column 3 is 11.5

Here is the code I have so far:

def sumColumn(matrix, columnIndex):
    total = (sum(matrix[:,columnIndex]) for i in range(4))
    column0 = (sum(matrix[:,columnIndex]) for i in range(4))

    print("The total is: ", total)
    return total

def main ():
    for r in range(3):
        user_input = [input("Enter a 3-by-4 matrix row for row " + str(r) + ":", )]
        user_input = int()


    rows = 3
    columns = 4
    matrix = []
    for row in range(rows):
        matrix.append([numbers] * columns)
        print (matrix)

main()

 it prints out:
[[0, 0, 0, 0]]
[[0, 0, 0, 0], [0, 0, 0, 0]]
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

What am I doing wrong?

1
I have this assignment is the immediate turn-off. - Malik Brahimi

1 Answers

0
votes

You should probably just use this as a reference otherwise you'll never learn anything

PROMPT = "Enter a 3-by-4 matrix row for row %s:"

def sumColumn(matrix, columnIndex):

    return sum([row[columnIndex] for row in matrix])

def displayMatrix(matrix):

    #print an empty line so that the programs output matches the sample output
    print

    print "The matrix is"
    for row in matrix:
        print " ".join([str(col) for col in row])

    #another empty line
    print

    for columnIndex in range(4):
        colSum = sumColumn(matrix, columnIndex)
        print "Sum of elements for column %s is %s" % (columnIndex, colSum)

def main ():

    matrix = [map(float, raw_input(PROMPT % row).split()) for row in range(3)]
    displayMatrix(matrix)

if __name__ == "__main__":
    main()