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

Time:04-27

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.

CodePudding user response:

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)
  • Related