Please find the problem and resolve it. I am not able to add the two matrices.
import random
m1 = int(input("Enter total number of rows in the first matrix\n"))
n1 = int(input("Enter total number of columns in the first matrix\n"))
a = [[random.random() for j in range(n1)]for i in range(m1)]
print("Enter the values in the first matrix one by one")
for i in range(m1):
for j in range(n1):
a[i][j] = input()
m2 = int(input("Enter total number of rows in the second matrix\n"))
n2 = int(input("Enter total number of columns in the second matrix\n"))
b = [[random.random() for j in range(n2)]for i in range(m2)]
if (m1==m2 and n1==n2):
print("Enter the values in the second matrix one by one")
for i in range(m2):
for j in range(n2):
b[i][j] = input()
print("The first matrix is")
for i in range(m1):
for j in range(n1):
print(a[i][j], end= "\t")
print()
print("The second matrix is")
for i in range(m1):
for j in range(n1):
print(b[i][j], end= "\t")
print()
c = [[random.random()for j in range(n1)]for i in range(m1)]
print("The sum of the matrix is")
for i in range(m1):
for j in range(n1):
c[i][j] = a[i][j] + b[i][j]
for i in range(m1):`enter code here`
for j in range(n1):
print(c[i][j], end= "\t")
print()
I have used all the ways given on other posts like using c[i][j] = [x+y for x,y in zip(a,b)] etc. but it always give the same output like if i have the matrix as [1 2] and [2 3] then the sum c will be [12 23] while it should have been c = [3 5]
I want to thank in advanced and want to tell you that i am a new computer science student, just going through the basics. So , please help.
Aucun commentaire:
Enregistrer un commentaire