How can I simplify these two functions?

Asked

Viewed 86 times

-3

This code sums the columns and rows of a matrix separately. I created these two functions to do this and I need to simplify my code by transforming them into one. Note that the only thing that changes is matriz[j][i] for matriz[i][j]. There is a way to call only one function by changing only the parameter?

def somar_linhas():
    soma = 0
    for i in range(4):
        for j in range(4):
            soma = soma + matriz[i][j]
        print(f"A soma da linha {i + 1} é {soma}")
        soma = 0


def somar_colunas():
    soma = 0
    for i in range(4):
        for j in range(4):
            soma = soma + matriz[j][i]
        print(f"A soma da coluna {i + 1} é {soma}")
        soma = 0


matriz = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12,], [13, 14, 15, 16]]

somar_linhas()
print()
somar_colunas()
  • 1

    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

  • Try using the numpy module

2 answers

3

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

0

To create a function that disappears or linhas or colunas, the function should receive a parameter indicating what it should add.

From there, a conditional chooses which parameters to add, as well as which texts to print:

def somar(colunas = False):
    soma = 0
    for i in range(4):
        for j in range(4):
            if(colunas):
                soma = soma + matriz[j][i]
            else:
                soma = soma + matriz[i][j]
        if(colunas): 
            tipo = 'colunas'
            indice = j
        else:
            tipo = 'linhas'
            indice = i 
        print(f'A soma da {tipo} {indice+1} é {soma}') 
        soma = 0
    indice = 0

In this function, calling somar() (no parameters) or soma(False) (default) the sum of rows.

And the call somar(True) will sum the columns.

Browser other questions tagged

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