Add Two Matrices
Write a program to add the two matrices. To add two matrices, just add the corresponding entries, and place this sum in the corresponding position in the result matrix.
Input
The first line of input will contain two space-separated integers, denoting the M and N.
The next M following lines will contain space-separated integers, denoting the elements of each list for first matrix.
The next M following lines will contain space-separated integers, denoting the elements of each list for second matrix.
Output
The output should be M lines.
Each line should contain a row in the matrix as a list after adding two matrices.
Explanation
For example, if the given M is 3 and N is 3, read the inputs for first matrix in the next three lines. If the numbers for the first matrix are the following.
1 2 3
10 20 30
5 10 15
Read the inputs for second matrix in the next three lines. If the numbers for the second matrix are the following.
2 4 6
11 22 33
7 14 21
By adding the elements at the same location in both the matrices will give the required matrix. So the output should be
[3, 6, 9]
[21, 42, 63]
[12, 24, 36]
Sample Input 1
3 3
1 2 3
10 20 330
5 10 15
2 4 6
11 22 33
7 14 21
Sample Output 1
[3, 6, 9]
[21, 42, 63]
[12, 24, 36]
Code:
def add_two_matrices(first_matrix, second_matrix, m, n):
result=[]
for i in range(m):
row_result=[]
for j in range(n):
value=first_matrix[i][j]+second_matrix[i][j]
row_result.append(value)
result.append(row_result)
return result
def convert_string_to_int(list_a):
new_list = []
for item in list_a:
num = int(item)
new_list.append(num)
return new_list
def read_matrix_inputs(m):
num_list = []
for i in range(m):
list_a = input().split()
list_a = convert_string_to_int(list_a)
num_list.append(list_a)
return num_list
m, n = input().split()
m, n = int(m), int(n)
first_matrix = read_matrix_inputs(m)
second_matrix = read_matrix_inputs(m)
result=add_two_matrices(first_matrix, second_matrix, m, n)
for i in result:
print(i)
Input
1 5
-50 20 3 25 -20
88 17 38 72 -10
Output
[38, 37, 41, 97, -30]