Problem #1 at Project Euler is, besides being the problem with the most solutions provided to it, happens to also be a pretty good place to start working our way through the process.
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.
This is a simple problem as well as a good way to start using generators in Python.
def multiples( the_max ): for number in xrange( 1, the_max+1 ): if not number % 3 or not number % 5: yield number import time t2 = time.time( ) print sum( multiples( 1000 ) ), time.time( ) - t2
The function multiples is the generator that I’m using to produce the natural numbers from 1 to 1000. Because it takes a parameter it could generate numbers to any desired range.
In any case, it continuously steps through the numbers in the desired range, checks if they are a multiple of 3 or 5 (not number %3 or not number %5). If that is true, it yields the number and returns control back to the calling loop, which in this case is the standard function sum, which adds the values returned by an iterator.
It’s true that this problem could be solved just as easily using regular functions, but half the fun of working through the Project Euler problems is in finding new ways of completing the problems (such as by using a language that is new to you).