script that to find the sum of multiples of 3 in array – Python script question

Question:

Currently working with this script snippet:

values = [1, 3, "5", 7, 8, 9]
multiples_of_three = []
total_of_threes = 0

#find 3s
while not (i > values. length):
    if (values[i] % 3):
        multiples_of_three[i] = values[i]

#do sum
while True:
    if not multiples_of_three.empty():
        total_of_threes = total_of_threes + multiples_of_three.first_item
        multiples_of_three.remove_first_item
    elif multiples_of_three.empty():
        break

print(total_of_threes)

and running into error:

Traceback (most recent call last):
  File "<string>", line 5, in <module>
NameError: name 'i' is not defined

Any idea on how this could be solved?

Asked By: Polacan

||

Answers:

you need to declare your i variable before using it

values = [1, 3, "5", 7, 8, 9]
multiples_of_three = []
total_of_threes = 0
i = 0

anyway, you should check your code, you are trying to use methods that doesnt exist.

Answered By: Matías Rivas

There are multiple incoherences in your code (missing variable definitions, inexistent methods…). In addition, the style is not that of python, you wouldn’t use a while loop to iterate over elements of a list.

A pythonic approach would be to use a list comprehension.

Here an example for python ≥ 3.8:

values = [1, 3, "5", 7, 8, 9]

out = sum(i for x in values if (i:=int(x))%3 == 0)

Output: 12

If you want to ignore strings:

out = sum(x for x in values
          if isinstance(x, (int, float))
          and x%3 == 0)
Answered By: mozway
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.