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


Copyright © 2022 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion and http://snippets.bentasker.i2p
hit counter