Created
April 22, 2020 12:04
-
-
Save vicradon/27e495f24ac7cae9175640575593b332 to your computer and use it in GitHub Desktop.
The Fibonacci even sequence reducer
This file contains hidden or 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
def fib(n): | |
''' | |
This function returns a fibonacci seq assuming the seq starts as [1, 2] | |
''' | |
try: | |
sequence = [] | |
if n == 1: | |
sequence = [1] | |
if n >= 2: | |
sequence = [1, 2] | |
if n < 1: | |
raise ValueError | |
if type(n) is not(int): | |
raise TypeError | |
if n > 4000000: | |
raise OverflowError | |
def recur(n): | |
for _ in range(n-2): | |
sequence.append(sequence[-1] + sequence[-2]) | |
recur(n) | |
return sequence | |
except ValueError: | |
print("Value must be greater than 1") | |
return '' | |
except TypeError: | |
print("Input must be of type 'int'") | |
return '' | |
except OverflowError: | |
print("Input is out of range") | |
return '' | |
# Test the fib function | |
''' | |
print(fib(5)) | |
print(fib(-1)) | |
print(fib('dndk')) | |
''' | |
def sum_of_even_fib_terms(n): | |
''' | |
This function returns the sum of the sum of the even terms of a fibonacci sequence | |
''' | |
seq = fib(n) | |
if type(seq) is str: return 'Try not to input wrong values next time' | |
even_terms = list(filter(lambda x: x%2==0, seq)) | |
return sum(even_terms) | |
print(sum_of_even_fib_terms(9)) | |
print(sum_of_even_fib_terms(-9)) | |
print(sum_of_even_fib_terms(4000001)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment