KishCom

Developer. Gamer. Yo-Yo Thrower.

Python generators

Learning about Python generators. O_O Awesome.

The problem: Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million. (This is actually problem #2 in Project Euler – the best way to get acquainted with new languages IMO)

In PHP:

$fibSeq = 0;
$prev = 1;
$prevPrev = 0;
$count = 0;
do{
        $fibSeq = $prev + $prevPrev;
        $prevPrev = $prev;
        $prev = $fibSeq;
        if (($fibSeq % 2) == 0){
                $count += $fibSeq;
        }
}while($fibSeq < 3524577);
echo $count;

Now the same thing in Python using a generator:

def fib():
    a, b = 0, 1
    while 1:
        if ((a % 2) == 0):
                yield a
        a, b = b, a + b

fib = fib()
fibSum = 0
while fibSum < 3524577:
    nextFib = fib.next()
    fibSum += nextFib
print fibSum

So much nicer isn't it?

Back to KishCom.com
KishCom.Com

Table of Contents