Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add certain values that were produced in a 'while' loop using Python

I was solving a Project Euler problem that goes as follows:

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."

So I used this script to print the Fibonacci sequence up to four million:

a = 0
b = 1
while b < 4000000:
    print b
    a, b = b, a+b

Obviously, I could run this and just manually add the even values, but I would feel like I'm cheating.

Technically, I guess I'm asking two questions:

  1. How could I pick out the evens?
  2. How could I add those evens without actually assigning them to a variable?

Oh, and I'm sure its extremely evident, but I'm very new to...well, programming in general and I can get lost in experts' verbosity easily. Thanks in advance!

like image 832
Grant Avatar asked Jan 18 '23 23:01

Grant


2 Answers

If you're averse to variable assignments, you might enjoy a functional approach:

>>> from itertools import takewhile, ifilter

>>> def fib():
        a, b = 0, 1
        while True:
            yield a
            a, b = b, a+b

>>> def is_even(x):
        return x % 2 == 0

>>> sum(ifilter(is_even, (takewhile(lambda x: x<4000000, fib()))))
4613732
like image 123
Raymond Hettinger Avatar answered Jan 28 '23 16:01

Raymond Hettinger


Ah, Project Euler!

This is more a math question than a programming question, though.

On the programming side, simply add an accumulator. You can test for evenness by using the modulo operator %, which returns the integer remainder after dividing the left operand by the right operand.

a, b = 0, 1
evens = 0
while b < 4000000:
    if not b%2:
        evens += b
    a, b = b, a+b

Once you have the answer, the Project Euler PDF and forums will fill you in on the mathy part of this problem and really answer your questions. There are ways to avoid having to calculate every Fibonacci number and having to test for evenness, but these require exploiting specific mathematical properties of the Fibonacci sequence.

like image 28
Francis Avila Avatar answered Jan 28 '23 14:01

Francis Avila