Python practice problem

Given a square matrix M, write a function DiagCalc which calculate the sum of left and right diagonals and print it respectively.(input will be handled by us)


Input:

A matrix M 
[[1,2,3],[3,4,5],[6,7,8]] 

Output 
13
13

Explanation:
Sum of left diagonal is 1+4+8 = 13
Sum of right diagonal is 3+4+6 = 13

SOLUTION:
#Input the values for the matrix

a=[]

n=int(input("Enter the order of the matrix:"))
for i in range(n):
    l=[]
    for j in range(n):
        val=int(input("Enter the element of the matrix"))
        l.append(val)
    a.append(l)
   
#Calculating the sum of the left diagonals


    def left(a):
        left_diag=0
        for i in range(n):
            for j in range(n):
                if(i==j):
                    left_diag = left_diag+a[i][j]
               
        return left_diag

    #Calculating the sum of the right diagonals
    def right(a):
        right_diag=0
        for i in range(n):
            for j in range(n):
                if(i+j==n-1):
                    right_diag = right_diag + a[i][j]
               
        return right_diag


ans1=right(a)
ans2=left(a)

print("The sum of the left diagonals is ",ans2)
print("The sum of the right diagonals is ",ans1)

Comments

Popular Posts