Identify if a matrix is triangular upper, lower or diagonal

Asked

Viewed 497 times

-2

I need to receive a matrix and identify if it is an upper triangular matrix, a lower triangular matrix or a diagonal matrix (upper+lower)

I wrote a code initially to find out if it is diagonal (since for me it would be a little easier), but neither it is running, exploring the variables I realize that the counter is not increasing, IE, the function is not running, but the program does not return error anywhere.

Follow the program:

n = int(input())

M = []
for a in range(n):
    M.append(input().split(" "))

print(M)

linhas = len(M)
colunas = len(M[0])

cont = 0

for i in range(linhas):
    for j in range(colunas):
        if i != j and M[i][j] == 0:
            cont = cont + 1

if cont == 2*n:
    print("diagonal")
  • To be more readable, try to do a "Ctrl +K" in the code part so you can post here.

  • Another detail, your matrix is receiving a string, that is, when you check whether M[i][j] == 0, it will fail, because in fact M[i][j] is "0". To make it easier, just do the following: M.append([int(x) for x in input().split(" ")]), which ai Oce already receives the values as integers.

1 answer

0

I find it easier to assume that the matrix is higher and lower and prove otherwise in each case.

To check if the matrix is not lower just check if there is any element in an index column larger than the row that is not zero. Does something similar to check if the matrix is not superior.

print("Digite o número de linhas")
n = int(input())

M = []
for a in range(n):
    print("Digite os elementos na linha {} separados por espaço".format(a))
    M.append([int(x) for x in input().split(" ")])

linhas = len(M)
colunas = len(M[0])


# Vamos assumir inicialmente que a matriz é superior
a_matriz_e_sup = True
# e inferior também
a_matriz_e_inf = True

for i in range(linhas):
    # Só precisamos verificar colunas maiores que 'i' e temos certeza que 'i' e
    # 'j' nunca serão iguais (não precisamos de "i != j" no "if"
    for j in range(i+1, colunas):
        if M[i][j] != 0:
            # Se encontrarmos algum elemento diferente de zero em ao menos uma
            # coluna de índice maior que o índice da linha então a matriz não
            # pode ser inferior
            a_matriz_e_inf = False

for i in range(1, linhas):
    for j in range(0, i):
        if M[i][j] != 0:
            # Semelhante ao caso anterior
            a_matriz_e_sup = False

print("Matriz")
for linha in M:
    print(linha)

if a_matriz_e_sup and a_matriz_e_inf:
    print("diagonal")
else:
    if a_matriz_e_sup:
        print("superior")
    if a_matriz_e_inf:
        print("inferior")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.