Sum of elements in lists

Asked

Viewed 8,348 times

0

[[3, 2, 7], [8, -2, 5], [-1, 4, 3], [2, 2, -9]]

Then it stores in three distinct variables, ignoring the negative values, the sum of the elements separately. That is, the sum of the first element of each sub-list, the sum of the second element of each sub-list and the sum of the third element of each sublist. Then create a dictionary with the key/value match of the numbers 1 to 15, for example:

{1:"Um", 2:"Dois" … 15:"Quinze"}.

Finally, by matching the result value to the dictionary key, it presents the result individually in text form.

I started with this code. My first question is to cycle for if else? How do I get only the positives added? What do I call the blocks? In the same way as in the lists 0,1,2,3?

lista=[[3,2,7], [8,-2,5], [-1,4,3], [2,2,-9]]

var1=""
var2=""
var3=""

for int in range(len(lista))
    if (int in lista)
    var1= 

2 answers

2


Consider the entry list:

values = [[3, 2, 7], [8, -2, 5], [-1, 4, 3], [2, 2, -9]]

Wishing to add the values of each list to a given index, we must then reset the list according to our need. To do this, we use the native function zip:

values = list(zip(*values))

Note: Use the * causes each list position to be passed as a parameter to the function. Do zip(*values) is the equivalent of zip(values[0], values[1], values[2]), but with less code and much easier to read.

In this way, our list will be as follows:

[(3, 8, -1, 2), (2, -2, 4, 2), (7, 5, 3, -9)]

That is, a tuple was created with the values in the index 0 of each list, another with the values of the index 1 and another with the values in the index 2. It is now enough to add the values when they are not negative, storing the result in variables, using the native function sum.

sum_1 = sum(i for i in values[0] if i >= 0) # Resulta: 13
sum_2 = sum(i for i in values[1] if i >= 0) # Resulta: 8
sum_3 = sum(i for i in values[2] if i >= 0) # Resulta: 15

It is also requested to define a dictionary with the numbers in full. Like this:

texts = {
  1: "um",
  2: "dois",
  3: "três",
  4: "quatro",
  5: "cinco",
  6: "seis",
  7: "sete",
  8: "oito",
  9: "nove",
  10: "dez",
  11: "onze",
  12: "doze",
  13: "treze",
  14: "catorze",
  15: "quinze",
}

Finally, the result is presented:

print("A soma 1 resultou em: {}".format(texts[sum_1]))
print("A soma 2 resultou em: {}".format(texts[sum_2]))
print("A soma 3 resultou em: {}".format(texts[sum_3]))

That will be:

A soma 1 resultou em: treze
A soma 2 resultou em: oito
A soma 3 resultou em: quinze

See the code working on Repl.it or in the Ideone.

  • The problem of using a dictionary like this and that if the sum results in a number that is not in a dictionary the program would report an error, so it would have to use error handling and even then it would not get an expected result. Another point is that saving the results in variables can result in new errors if the matrix is larger.

  • @Arcashaid, indeed, but the statement explicitly asks this way and, considering an exercise solution, ALL requirements raised by the statement must be satisfied.

  • The problem is that the statement does not specify the size of columns

  • There will always be three values in each sub-list, it is clear that in: the sum of the first element of each sub-list, the sum of the second element of each sub-list and the sum of the third element of each sub-list.

0

You need to face the problem as a matrix (which is accessed: matriz[posicao_i][posicao_j]))

1. Fix the column and traverse all lines, then making your conditions and operations; 2. increase the column position; 3. repeat.

# para somar ignorando os valores negativos:

lista = [[3,2,7], [8,-2,5], [-1,4,3], [2,2,-9]]

valores = []

for coluna in range(len(lista[0])):
    soma = 0

    for linha in range(len(lista)):
        if(lista[linha][coluna] >= 0):
            soma += lista[linha][coluna]

    valores.append(soma)

print(valores)
  • Thanks now I only have to store the result in different variables.

  • As much as it can solve the problem, this solution is not considered good in Python. Make better use of the language tools and you will get much more interesting results. Always seek to analyze which is the most pythonica.

Browser other questions tagged

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