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

Remotely backing up PFsense Configuration (BASH)
FFMPEG: Converting RMVB to X264 MP4 (BASH)
Recursively print table (print_r equivalent) (LUA)
Bulk Delete Comments from (Self-Hosted) JIRA Issues (Misc)
Add a static entry to the ARP table (BASH)
SSL Cipher Hex codes to Human Readable Names (Misc)
Convert Ascii to Binary (BASH)
Intercepting Outbound DNS Queries (BASH)
Handle Google Verification files within NGinx Configuration (NGinx)
Getting WhatsApp Rich Snippet Previews Working (Misc)

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