Problem: Add the given 2 matrixes.
Solution in Python:
def add(A, B):
"""
Author: Mayur P Srivastava
"""
m1, n1 = shape(A)
m2, n2 = shape(B)
if not can_add(m1, n1, m2, n2):
return None
C = create_matrix(m1, n2)
for i in range(m1):
for j in range(n2):
C[i][j] = A[i][j] + B[i][j]
return C
def shape(A):
m = len(A)
n = 0
for row in A:
n2 = len(row)
if n == 0:
n = n2
elif n != n2:
assert False
return m, n
def can_add(m1, n1, m2, n2):
return m1 == m2 and n1 == n2
def create_matrix(m, n, value=0):
matrix = []
for i in range(m):
row = []
for j in range(n):
row.append(value)
matrix.append(row)
return matrix
Concepts Learned: Nested loops and Maths
No comments:
Post a Comment