Home > Net >  How to sum up all numbers in a list that are divisible by 2 numbers
How to sum up all numbers in a list that are divisible by 2 numbers

Time:10-15

Hello (sorry for bad English) i have been working around trying to find out how to sum up all numbers in a list that are divisible by 2 numbers. i am not sure what too add to my code to get it right.

let's say we have a range of numbers from 0-100 and i want to find out what numbers are divisible by 3 or 10. i have calculated the sum of this and the answer should be 1953 if i haven't calculated wrong.

list = list(range(100))
x=0
for x in list:
    x=(x 1//10==0)
    print (x)

the output of this is just the row of numbers from 0-100. i have tried searching for clues, but i have only seen programs where the list is made with just around 4 numbers which where given and not a range like mine. if anyone know a sulution too this problem it would help a lot

CodePudding user response:

Here is a solution written (almost) entirely by AI:

Solution

def sum_divisible_by(numbers, divisor1, divisor2):
    return sum(x for x in numbers if x % divisor1 == 0 or x % divisor2 == 0)

Explanation

The solution is a one-liner. It uses a generator expression to filter the numbers that are divisible by the divisor.

CodePudding user response:

You can use: divisors = [i for i in original_list if i%3 == 0 or i == 0].
If you want the sum - s = sum(divisors).

CodePudding user response:

use a custom function to create your list and mod 2 to find the even numbers

def createList(r1, r2):
    return [item for item in range(r1, r2 1)]

myList = createList(0,100)
result=[item for item in myList if item%2==0]
print(result)

CodePudding user response:

There are several problems with the line x=(x 1//10==0):

  • it should probably be (x 1)//10, not x 1//10, but if you want to get 1953, 100 seems not to be included, so rather just x, not x 1
  • with // you do integer division, you do not get the remainder; for that, use modulo %
  • you assign the result of the comparison back to x; instead that should probably be an if condition, and if that's true, add x to a running sum and not just print it
  • you only test for one divisor, not for both

With that, your code would become this, which yields 1953 as expected:

res = 0
for x in range(100):
    if x % 3 == 0 or x % 10 == 0:
        res  = x

Or shorter, using the sum builtin function with a generator expression:

res = sum(x for x in range(100) if x % 3 == 0 or x % 10 == 0)
  • Related