Search code examples
python-3.xfundamentals-ts

Stuck with Matrix addition in python


Please look at my code for matrix addition in python and help me to resolve the issue.

Code:

def matrix_addition(a, b):
# your code here
res = []  
for i in range(len(a)):
    for j in range(len(b)):
        sum = a[i][j] + b[i][j]
        res.append(sum)
return res

matrix_addition( [ [1, 2],[1, 2] ], [ [2, 3],[2, 3] ] )

Expected output: [[3, 5], [3, 5]]

My output: [3, 5, 3, 5]

How to initialise the nested list and have some variables in it?

PS: I'm a beginner in Python, so expecting easier solution :)


Solution

  • For beginner in Python, take very particular attention to the indentation because is the base of Python syntax, no end delimiter like majority of languages/scripts.

    You don't create an array for sum and you don't append it on the right loop. Try this :

    def matrix_addition(a, b):
    # your code here
    res = []  
    for i in range(len(a)):
        sum = []
        for j in range(len(b)):
            sum.append([i][j] + b[i][j])
        res.append(sum)
    return res