The things I'm interested the most from the review are:
- The performance of the code
- Overall review of the code structure, styling rules and naming conventions.
Problem: 2
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
import math
import itertools
#----------------------------------------------------------------------------------
def calc_fibonacci_num(n):
"""Calculates the fibonacci number at the given index.
Arguments:
type:<int> - Index value of the fibonacci sequence
Return:
type:<int> - Fibonacci number at the given index.
"""
return int(((1 + math.sqrt(5))**n -(1 - math.sqrt(5))**n)/(2**n*math.sqrt(5)))
#----------------------------------------------------------------------------------
def calc_fibonacci_seq(n):
"""Generates the fibonacci sequence with the highest
value equal to or less then the number provided by the user.
Arguments:
type:<int> - Thrshold value for the fibonacci sequence.
Return:
type:<arr> - An array holding the fibonacci sequence.
"""
return [calc_fibonacci_num(x) for x in itertools.takewhile(lambda x: calc_fibonacci_num(x) <= n, itertools.count())]
#----------------------------------------------------------------------------------
def calc_fibonacci_sum(n, d = 0):
"""Calculates the sum of the numbers in fibonacci sequence.
Filtering of the numbers to be added is controled with the module operator.
Arguments:
type:<int> - Thrshold value for the fibonacci sequence.
type:<int> - Division value for module operation.
Return:
type:<int> - The sum of the numbers in the fibonacci sequence.
"""
if d > 1 :
return sum(x for x in calc_fibonacci_seq(n) if x % d == 0)
return sum(x for x in calc_fibonacci_seq(n))
#----------------------------------------------------------------------------------
def main():
print(' Fibonacci-seq : {}'.format(calc_fibonacci_seq(4000000)))
print(' Fibonacci-sum : {}'.format(calc_fibonacci_sum(4000000, 2)))
#----------------------------------------------------------------------------------
if __name__ == "__main__":
main()
fibonacci_sum
function, this might be interesting: from what I can see, everyx
th fibonacci numer is divisible byy
, withy = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
andx = [1, 3, 4, 6, 5, 12, 8, 6, 12, 15, 10, 12, 7, 24, 20]
. I can't figure out how the sequence works, but it seems to continue. If you have higher modulii (and your floating point arithmetic holds out) there may be a way to use your method more efficiently then simple accumulation. \$\endgroup\$