Calculate Fibonacci Sequences



Published: 2017-05-21 11:57:56 +0000
Categories: Python,

Language

Python

Description

A small function to calculate Fibonacci like sequences based on provided seed values. Can be used to calculate Fibonacci numbers, Lucas numbers or an arbitrary Fibonacci like sequence

We're simply calculating Fn = Fn-1 + Fn-2 for a given number of iterations

When called without arguments, the default behaviour is to return the first 12 numbers of Fibonacci

Returns a list of numbers in the sequence, with the provided seeds at the beginning

Similar to

Snippet

def calculateFibonacciSequence(F1=1,F2=1,count=10):
    ''' Calculate a Fibonnaci like sequence

        args:
            F1      Seed 1
            F2      Seed 2
            count   number of numbers to generate (after the seed)

        return list
    '''
    numbers = []

    # Push the seeds to the list
    numbers.append(F1)
    numbers.append(F2)

    x = 1

    while x <= count:
        # Calculate the next number
        new = F1 + F2
        numbers.append(new)

        # Set the seeds for the next iteration
        F1 = F2
        F2 = new
        x = x + 1

    return numbers

Usage Example

# Calculate Fibonnaci numbers
print calculateFibonacciSequence(count=15)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]

# Calculate Lucas Numbers
print calculateFibonacciSequence(2,1,15)
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322, 521, 843, 1364, 2207]

License

BSD-3-Clause

Keywords

Fibonacci, Fibonnacci, Lucas, Numbers, integer, sequences, calculate,

Latest Posts

Urldecode string (LUA)
FFMPEG Convert YUV444p to YUV420p (BASH)
Forcing FFMPEG to honour segment length in HLS Stream Creator (BASH)
Force CURL to place request to a specific IP (BASH)
Set a variable only if it is undefined (Javascript)
Ignore query string with Nginx caching proxy (NGinx)
Get breakdown of UK and non-UK votes for a Parliamentary Petition (Python)
Decompress Mozilla Firefox jsonlz4 bookmark backup files (Python)
Setting Git author details for a single repo (Git)
Checking Virtual Machine Resource Allocations with Libvirt (BASH)

Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk and snippets.6zdgh5a5e6zpchdz.onion