Fibonacci in Python compared to C-style Languages

I have played around with Python these past few months. Learning Python will make you realize some of the not so good things about PHP and other similar C-style Languages. But I’m not going to delve into their comparison, you can find a good article about that subject here.

What got me intrigued is how I was able to implement the classic Fibonacci function in Python without having to use an extra variable that should be present in both PHP or Javascript implementation.

First I’ll show you how it is implemented in both JavaScript and PHP:

JavaScript: (Copy and run in your browser’s JS console to see it in action now!)

<script type="text/javascript">
function fib(n)
{
    var a = 0, b = 1;
    while(b < n) {
        console.log(b);
        sum = a + b;
        a = b;
        b = sum;
    }
}

fib(60);
</script>

PHP:

<?php
function fib($n)
{
    $a = 0, $b = 1;
    while($b < $n) {
        echo $b . PHP_EOL;
        $sum = $a + $b;
        $a = $b;
        $b = $sum;
    }
}

fib(60);
?>

You’ll notice that both JavaScript and PHP use the following variables: n, a, b, and sum. Variable n will be the size or the limit of the series while a, b and sum are there to help determine what numbers to display.

Now it’s Python’s turn:

def fib(n):
    a, b = 0, 1
    while(b < n):
        print(b)
        a, b = b, a + b
       
fib(60)

For Python, it doesn’t need to use the extra variable sum. This is because you can assign variables simultaneously in Python just like in Ruby and Perl.

This is one of those little things that we might overlook when building applications. Yes, we only saved one variable in this Fibonacci function. But how much more when we build more complex applications? When we’ll need to strategically assign variables in large and scalable applications?

  1. Very Good. Thank you!

    [WORDPRESS HASHCASH] The poster sent us ’994879936 which is not a hashcash value.

  2. You’re welcome!

    [WORDPRESS HASHCASH] The poster sent us ’0 which is not a hashcash value.

  3. Here is an alternate php version:

    function fib($n)
    {
    list($a, $b) = array(0, 1);
    while($b < $n) {
    echo $b . PHP_EOL;
    list($a, $b) = array($b, $a + $b);
    }
    }

  4. cool! wow never thought of this. thanks shaun

    [WORDPRESS HASHCASH] The poster sent us ’0 which is not a hashcash value.

Leave a Comment


six + = 14


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>