This notebook has a minor addition to euler-001-multiples-of-3-and-5-20160319.ipynb.
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.
In [1]:
from __future__ import print_function
...
I will have another go at the union thing, this time as a function.
In [29]:
def union(sets):
u = set([])
for s in sets:
u |= s
return u
In [30]:
def foo(n, divisors):
return sum(union(set(range(0, n, d)) for d in divisors))
In [31]:
n=1000
divisors = (3, 5)
%timeit foo(n, divisors)
foo(n, divisors)
Out[31]:
It works, but is not as readable, so forget it.
2016-06-29: I have another way of writing the union function from above, this time using reduce() instead of iterating through a loop. Why did I not think of reduce() earlier?
The code and output above is preserved as it ran on 2016-03-19 in Python 2. The code and output below ran on 2016-06-29 in Python 3.
In [1]:
from functools import reduce
from operator import or_
In [2]:
def union(sets):
return reduce(or_, sets)
In [3]:
def foo(n, divisors):
return sum(union(set(range(0, n, d)) for d in divisors))
In [4]:
n=1000
divisors = (3, 5)
%timeit foo(n, divisors)
foo(n, divisors)
Out[4]: