Consider a square matrix , a size n*n and a integer , x . Calculate the row number , r and column , c or x in a. If the sum of R and C is an even number, find the sum s of all even numbers in the matrix and if the sum of r and c is odd , then find the sum s of all odd numbers in the matrix.
def fun(a):
r = len(a)
c = len(a[0])
x = r + c
s = 0
for i in range(r):
for j in range(c):
if a[i][j]%2 == x%2:
# if a[i][j] has the same odd parity as x
s += a[i][j]
return s
import random
r = 3
c = 3
a = []
for i in range(r):
a.append([random.randint(0, 9) for _ in range(c)])
print("Matrix a:", a)
for i in range(r):
print(a[i])
print("fun(a) =", fun(a))
Comments
Leave a comment