Check for Fibonacci Like Sequence



Published: 2017-05-21 11:41:34 +0000
Categories: Python,

Language

Python

Description

Takes 3 values, and calculates whether they appear to be part of a Fibonacci integer sequence (i.e. g(n + 2) = g(n) + g(n + 1))

We only check if the sequence is Fibonacci like, not that the values are part of the Fibonacci sequence (for example, they may instead be a series of Lucas Numbers)

Values should be passed to the function in the order that they were observed

Return value is a list with two entries

  • Boolean - are the numbers part of a sequence?
  • Mixed - If part of a sequence, is the sequence running ascending (asc) or descending (desc). If not part of a sequence this values will be False

Used as part of the solution to my May 2016 Puzzle

Snippet

def isPartOfFibbonaciLikeSequence(Fn,Fn1,Fn2):
    ''' Check whether values form part of a Fibonnaci like sequence 
            i.e. does Fn = Fn-1 + Fn-2

            return [is sequence, direction of sequence]
        '''
    seq = False
    order = False

    # Sequences can be asc or desc, test both

    if Fn + Fn1 == Fn2:
        seq = True
        order = 'asc'
    elif Fn - Fn1 == Fn2:
        seq = True
        order = 'desc'

    return [seq,order]

Usage Example

print isPartOfFibbonaciLikeSequence(1,1,2)
[True, 'asc']

print isPartOfFibbonaciLikeSequence(1,2,3)
[True, 'asc']

print isPartOfFibbonaciLikeSequence(2,3,4)
[False, False]

print isPartOfFibbonaciLikeSequence(2,1,1)
[True, 'desc']

License

BSD-3-Clause

Keywords

Fibonacci, Fibonnacci, Lucas, integer, sequence, check,

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