165k views
0 votes
Write a function sum_of_rows_columns in a Python file named 1ab12_p2.py that takes a 2D list as a parameter and then returns a tuple containing two lists, the first list containing the sum of each row and the second list containing the sum of each column. Here is an example:

>>>sum_of_rows_columns ( [[1,2,3], [4,5,6], [7,8,9]])
([6, 15, 24], [12, 15, 18])

User Chazy Chaz
by
7.8k points

1 Answer

2 votes

Final answer:

The function sum_of_rows_columns is written in Python and takes a 2D list as input, returning a tuple with the sums of each row and column. It utilizes list comprehensions for the calculations and correctly produces the expected output as shown in the example given.

Step-by-step explanation:

To write a function sum_of_rows_columns in Python that takes a 2D list and returns a tuple of two lists, where the first list contains the sums of each row and the second contains the sums of each column, you would need to iterate over each row for the row sums, and each column for the column sums.

Below is the Python function that achieves this:

def sum_of_rows_columns(matrix):
row_sums = [sum(row) for row in matrix]
col_sums = [sum(matrix[row][col] for row in range(len(matrix))) for col in range(len(matrix[0]))]
return (row_sums, col_sums)

The function uses list comprehensions to create two lists: row_sums and col_sums. row_sums is straightforward, as it sums each row. col_sums sums up the elements in each column across all rows.

Calling sum_of_rows_columns([[1,2,3], [4,5,6], [7,8,9]]) would return the tuple ([6, 15, 24], [12, 15, 18]) as described.

User Amityo
by
8.7k points