How to Compute the nth Fibonacci Number

Posted by Prolific Programmer Thu, 13 Dec 2007 04:30:00 GMT

A fairly popular brainteaser that comes up repeatedly during my many job interviews. The answer is just one, leave comments if you have better ways. I'm aware that one can use Python generators to do this more efficiently, but I wanted to keep the code as clean as possible

def fib(n):
    '''Return the nth fibonacci number '''
    f=[1,1,2]
    for x in range(3,n):
        next = f[-1]+f[-2]
        f.append(next)
    return f[-1]

if __name__ == '__main__':
    import sys
    print fib(int(sys.argv[1]))
Comments

Leave a comment

Comments