Multiples of 3 and 5

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

V1


In [ ]:
# with the most 'conventional' and minimal 
# set of keywords, datastructures and constructs
i = 1  # counter
x = 0  # result
while i < 1000:
    if i % 3 == 0:
        x = x + i
    elif i % 5 == 0:
        x = x + i
    i = i + 1
x

V2


In [ ]:
# use a logic operator instead of if/elif
i = 1  # counter
x = 0  # result
while i < 1000:
    if i % 3 == 0 or i % 5 == 0:
        x = x + i
    i = i + 1
x

V3


In [ ]:
# instead of using a while loop and a counter
# explicitly iterate over 0 .. 999 with range() 
x = 0  # result
for i in range(1000):
    if i % 3 == 0 or i % 5 == 0:
        x = x + i
x

In [ ]:
# introducing augmented assignments 
x = 0  # result
for i in range(1000):
    if i % 3 == 0 or i % 5 == 0:
        x += i
x

Introducing aspects of functional programming


In [ ]:
# List comprehension
# instead of explicitly iterating 
# generate a list with all elements that fit the criteria 
l = [e for e in range(1000) if e % 3 == 0 or e % 5 == 0]
sum(l)

In [ ]:
# completely without any (visible) iteration
sum(filter(lambda e: e % 3 == 0 or e % 5 == 0, range(1000)))

In [ ]:
# Like Stefan suggested ... I guess I got it wrong though
from functools import reduce
from operator import add

reduce(add, [e for e in range(1000) if e % 3 == 0 or e % 5 == 0])

Extending the functionality

Parametrize the upper limit


In [ ]:
def mult_of_3_or_5(limit):
    return [e for e in range(limit) if e % 3 == 0 or e % 5 == 0]

sum(mult_of_3_or_5(1000))

Parametrize the numbers to be divisible by

V1


In [ ]:
def mult_of(limit, divisors):
    numbers = set()
    for e in range(limit):
        for divisor in divisors:
            if e % divisor == 0:
                numbers.add(e)
    return numbers

print(sum(mult_of(1000, [3, 5])))

V2


In [ ]:
# use set comprehension with any(iterable)
def mult_of(limit, divisors):
    return {e for e in range(limit) if 
               any(e % d == 0 for d in divisors)}

print(sum(mult_of(1000, [3, 5])))