SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
Lists
Exercise:
Programming Excercises
Question:1 | ISBN:978013274719 | Edition: 6

Question

(Sum elements column by column) Write a function that returns the sum of all the elements in a specified column in a matrix using the following header:
def sumColumn(m, columnIndex):
Write a test program that reads a 3 x 4 matrix and displays the sum of each column.
Here is a sample run:

Enter a 3-by-4 matrix row for row 0: 1.5 2 3 4                                   
Enter a 3-by-4 matrix row for row 1: 5.5 6 7 8                                   
Enter a 3-by-4 matrix row for row 2:  9.5 1 3 1 

Sum of the elements for column 0 is 16.5

 

Sum of the elements for column 1 is 9.0
Sum of the elements for column 2 is 13.0
Sum of the elements for column 3 is 13.0
 

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Sum elements column by column Program Code:

# Function to calculate the sum of elements in a specified column of a matrix
def sumColumn(m, columnIndex):
    total = 0
    for row in m:
        total += row[columnIndex]
    return total

# Test program
def main():
    matrix = []  # Initialize an empty matrix

    # Prompt the user to enter a 3x4 matrix
    for i in range(3):
        row = input(f"Enter a 3-by-4 matrix row for row {i}: ").split()
        row = [float(num) for num in row]  # Convert the input numbers to floats
        matrix.append(row)

    # Display the sum of each column
    for j in range(4):
        columnSum = sumColumn(matrix, j)
        print(f"Sum of the elements for column {j} is {columnSum}")

# Call the test program
main()

Executed Output:

Enter a 3-by-4 matrix row for row 0: 1.5 2 3 4
Enter a 3-by-4 matrix row for row 1: 5.5 6 7 8
Enter a 3-by-4 matrix row for row 2: 9.5 1 3 1

Sum of the elements for column 0 is 16.5
Sum of the elements for column 1 is 9.0
Sum of the elements for column 2 is 13.0
Sum of the elements for column 3 is 13.0

 

0 0

Discussions

Post the discussion to improve the above solution.