It is possible to simplify and unite its functions with the use of a conditional operator:
expressão1 "if" condição "else" expressão2
It works by testing the logical value of condição
and case:
condição == True
conditional operator returns expressão1
.
condição == False
conditional operator returns expressão2
.
Some changes are also welcome as the statement of the sum variable directly in its application scope and the use of a increased assignment statement +=
def somar4x4(linhas=False):
for i in range(4):
soma = 0
for j in range(4):
soma += matriz[i][j] if linhas else matriz[j][i]
print(f"A soma da {'linha' if linhas else 'coluna'} {i + 1} é {soma}")
matriz = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12,], [13, 14, 15, 16]]
somar4x4(linhas=True)
somar4x4(linhas=False)
Test the code on Repli.it
As it once was commented prefer to pass the matrix as a function parameter, because this way you make your code become reusable:
def somar4x4(m, linhas=False):
for i in range(4):
soma = 0
for j in range(4):
soma += m[i][j] if linhas else m[j][i]
print(f"A soma da {'linha' if linhas else 'coluna'} {i + 1} é {soma}")
matriz = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12,], [13, 14, 15, 16]]
somar4x4(matriz, linhas=True)
somar4x4(matriz, linhas=False)
Test the example on Repl.it
Can also be applied to built-in function sum()
to a list comprehension in nested iteration loop:
def somar4x4(m, linhas=False):
for i in range(4):
soma = sum([m[i][j] if linhas else m[j][i] for j in range(4)])
print(f"A soma da {'linha' if linhas else 'coluna'} {i + 1} é {soma}")
matriz = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12,], [13, 14, 15, 16]]
somar4x4(matriz, True)
somar4x4(matriz, False)
Test the code on Repl.it
Prefer to pass the matrix as a function parameter. The way you did, the functions only work for a single matrix. Using parameters, they become more generic and work for any matrix: https://ideone.com/AB79fi
– hkotsubo
Try using the numpy module
– Alexandre Simões