Last active
October 7, 2021 21:38
-
-
Save ankona/cdbcfe8ac2f879efa4639f11cb37aa7f to your computer and use it in GitHub Desktop.
determiine if input list is a valid subsection of the fibonacci sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import List | |
from collections.abc import Iterable | |
def generate_fib(start=None, stop=None) -> List[int]: | |
last, value = 0, 1 | |
while True: | |
if stop and value > stop: | |
break | |
if not start or value > start: | |
yield value + last | |
last, value = value, value + last | |
def is_fibby(l: Iterable[int]) -> bool: | |
if not l: | |
return False | |
gen_iter, i_iter = generate_fib(), iter(l) | |
i, value = next(i_iter), next(gen_iter) | |
while value < i: | |
value = next(gen_iter) | |
if value == i: | |
for pair in zip(gen_iter, i_iter): | |
if pair[0] != pair[1]: | |
return False | |
return True | |
return False | |
def is_fib_like(l: List[int]) -> bool: | |
""" | |
look for a fibonacci-like sequence of sums. ignore potential sequence mismatch | |
""" | |
if not l: | |
return False | |
if len(l) > 2: | |
rev_l = list(reversed(l)) | |
for i, fib_sum in enumerate(rev_l): | |
lhs_factor, rhs_factor = rev_l[i+2], rev_l[i+1] | |
if lhs_factor + rhs_factor != fib_sum: | |
return False | |
if i + 2 >= len(rev_l) - 1: | |
break | |
return True | |
return False | |
if __name__ == "__main__": | |
fib_like = is_fib_like([1, 1, 2]) | |
print('fib_like:', fib_like) | |
fib_like = is_fib_like([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]) | |
print('fib_like:', fib_like) | |
fib_like = is_fib_like([1, 1, 2, 3, 5, 8, 12, 21, 34, 55]) | |
print('fib_like:', fib_like) | |
inputs = [([3, 5, 8], True), ([3], True), ([3, 4, 5], False), ([3, 5, 8, 13, 21, 34], True), \ | |
([14, 21, 34], False), ([], False), ([1, 2], True), ([1, 2, 2], False), ([1, 2, 3], True), \ | |
([1, 2, 4], False), (generate_fib(stop=100), True), (generate_fib(20, 100), True)] | |
for input, expected in inputs: | |
fibalicious = is_fibby(input) | |
assert fibalicious == expected |
Also, the interface I was aiming for was that the input arg was an iterable, which is a forward iterator in PHP. I guess this would mean a next-able in python rather than an indexable list.
Now we can have the mathematical discussion about whether an empty sequence is a subsequence of any other sequence :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some test cases to try/discuss
[]
[1,2]