As a Code Kata, I’ve been working my way through the Project Euler stuff.
Here’s the problem.
Here’s my solution:
[highlight lang=py]
- A generator to derive the Fibonacci sequence
def fib():
x, y = 0, 1
yield x
yield y
while 1:
x, y = y, x+y
yield y
if name == ‘main’:
idx = 0
sum = 0
gen = fib()
while idx <= 4000000:
idx = gen.next()
if (g % 2 == 0): h = h+g
print h
[/highlight]
Note: You want to be careful how you use infinite generators like the ‘fib()’ I created above.
One guy on the forums noted:
Now, replacing an odd number with O and an even with E, we get: O, O, E, O, O, E, O, O, E, O, O, E, O, O, E…And so each third number is even. We don’t need to calculate the odd numbers. Starting from an two odd terms x, y, the series is: x, y, x + y, x + 2y, 2x + 3y, 3x + 5y