A simple Python script that generates an array containing any numbers of the Fibonacci sequence based on their integer indices. Can also accept negative integers. If the correct parameter is specified, it will return the array as a string instead.

The Fibonacci sequence can be defined as follows:

(phi^n - (1 - phi)^n) / sqrt(5)


fibonacci(3, 8, True) # Returns "2,3,5,8,13,21"


def fibonacci(s, e, asstr = False):
    sqrt5 = 5**0.5
    gratio = (1 + sqrt5)/2
    nums = []
    for i in range(s,e+1):
        n = int((gratio**i - (1 - gratio)**i)/(sqrt5))
        if (asstr == True): nums.append(str(n))
        else: nums.append(n)
    return nums;

Next Post Previous Post