Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to figure out how to sum only the even numbers in two matrix

rows = eval(input("enter the number of rows:"))
columns = eval(input("enter the numbers of columns:"))

matrix = []                                         
matrix2 = []
matrix3 = []

for i in range(0, rows):                            
   matrix.append([])
   for j in range (0,columns):
       val = eval(input("Enter a number:"))        
       matrix[i].append(val)                       
print(matrix)
for i in range(0, rows):                            
   matrix2.append([])
   for j in range (0,columns):
       val2 = eval(input("Enter a number:"))        
       matrix2[i].append(val2)
print(matrix2)



for i in range(0, rows):
 if i % 2 == 0:
   matrix3.append([])
   for j in range (0,columns):
       val3 = matrix[i][j] + matrix2[i][j]
       matrix3[i].append(val3)
print(matrix3)

I am stuck regarding finding out how to only add the even numbers into matrix 3. Was trying to use a basic function if % 2 == 0 which would tell me the even numbers but do not know where to go after that.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You’re testing the row numbers for evenness, not the numbers in the matrixes.

for row1, row2 in zip(matrix, matrix2):
    new_row = []
    for num1, num2 in zip(row1, row2):
        new_num = 0
        if num1 % 2 == 0:
            new_num += num1
        if num2 % 2 == 0:
            new_num += num2
        new_row.append(new_num)
    matrix2.append(new_row)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading