Fibonacci Calculator in Python

by Stephen Fluin 2009.03.17

Thanks to Python's arbitrary long integer representation, Python makes an idea language for the development of a Fibonacci calculator. Below is the source code for a program to calculate the nth digit of the sequence while at the same time verifying the previous digit. I have used this on a reddit comment trail about Fibonacci to verify the previous entry and generate my own entry.

#!/usr/bin/python                                                 
# -*- coding: utf-8 -*-                                           
import sys, math                                                  

print "Received %d and %s." % (int(sys.argv[1]), sys.argv[2:])
term = int(sys.argv[1])-1 #Give the term you want.
s= ""
value = int(s.join(sys.argv[2:]))
f = lambda v: [str(v)[i*10l:(i+1)*10] for i in range(int(math.ceil(len(str(v))/float(10))))]
t = lambda v: ' '.join(f(v))

a=1
b=1
for i in range(1,term):
        c=a+b
        a=b
        b=c
        if(i+2 > term): print c
        if (i == term-1):
                  if (value==c) :
                           print "fib(%d) is correct" % (term+1)
                           print "fib(%d) is n%s" % ((term+2),t(a+b))
                           print "fib(%d) is n%s" % ((term+3),t(a+b+b))
                  else: print "fib(%d) is incorrectn%d != %d" % ((term+1), value, c)

permalink