Search code examples
pythonmatrixdiagonal

Sum of elements below the main diagonal of a matrix python


Basically I have to write a program that creates a matrix of N by N and fills it with random numbers and calculates the sum of all the elements below the main diagonal of the matrix. I already did everything except the sum of elements and this is what I have

import random

def llenar_matriz(n):
    # Fills the matrix with random numbers between 1 and 99
    for r in range(n):
        fila = []
        for c in range(n):
            fila.append(random.randint(1,99))
        matriz.append(fila)
    return matriz

def imprimir_matriz(matriz):
    # Prints the matrix properly (makes every list go below the previous one)
    filas = len(matriz)
    columnas = len(matriz[0])
    for f in range(filas):
        for c in range(columnas):
            print ("%3d" %matriz[f][c], end="")
        print()

def suma_matriz(matriz):
     #This should make the sum of all the values below the main diagonal of the matrix
   

# Programa principal
lado = int(input("Ingrese el ancho de la matriz: ")) #input value that makes the matrix N by N
matriz = []
llenar_matriz(lado)
imprimir_matriz(matriz)
total = suma_matriz()

print("La suma de los numeros debajo de la diagonal principal de la matriz es: ",total)

What I need help with is with the function that is going to recieve the matrix and sum all the values below the main diagonal


Solution

  • Try this

    import random
    
    def llenar_matriz(n):
        # Fills the matrix with random numbers between 1 and 99
        matriz = []
        for r in range(n):
            fila = []
            for c in range(n):
                fila.append(random.randint(1,99))
            matriz.append(fila)
        return matriz
    
    def imprimir_matriz(matriz):
        filas = len(matriz)
        columnas = len(matriz[0])
        for f in range(filas):
            for c in range(columnas):
                print ("%3d" % matriz[f][c], end="")
            print()
    
    
    def suma_matriz(matriz):
         #This should make the sum of all the values below the main diagonal of the matrix
        sum = 0
        for i in range(len(matriz)):
            for j in range(len(matriz)):
                if i != j and i > j: 
                    sum += matriz[i][j]
        return sum
       
    
    # Programa principal
    lado = int(input("Ingrese el ancho de la matriz: ")) #input value that makes the matrix N by N
    matriz = llenar_matriz(lado)
    imprimir_matriz(matriz)
    total = suma_matriz(matriz)
    
    print("La suma de los numeros debajo de la diagonal principal de la matriz es: ",total)
    

    Gives output

    Ingrese el ancho de la matriz: 5
    77 22 19 46 77 
    32 14 39  2 61 
    92 26 54 56 92 
    24 73 37 40 16 
    27 34 51 35 39 
    La suma de los numeros debajo de la diagonal principal de la matriz es:  431