En svårighet som man som utvecklare många gånger ställs inför är om värdet vid vilket iterationen termineras skall inkluderas eller inte. Många gånger trillar man dit på ”off-by-one”-fel även som van utvecklare med många års erfarenhet.
E.W. Dijkstra har sagt mycket klokt och även i frågan om nollindexering så hade han en åsikt. I ”Why numbering should start at zero” så försvarar han tesen att man ska använda sig av nollindexering.
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""problem002.py: Each new term in the Fibonacci sequence is generated by
adding the previous two terms. By starting with 1 and 2, the first 10 terms
will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms."""
__author__ = 'Mats Wiklander'
__copyright__ = 'Copyright 2015, Mats Wiklander'
def main():
a = 0
b = 1
fibonacci_value = 0
fibonacci_sequence = []
while fibonacci_value < 4000000:
fibonacci_value = a + b
a = b
b = fibonacci_value
if fibonacci_value % 2 == 0:
fibonacci_sequence.append(fibonacci_value)
print sum(fibonacci_sequence)
if __name__ == '__main__':
main()
En svårighet som man som utvecklare många gånger ställs inför är om värdet vid vilket iterationen termineras skall inkluderas eller inte. Många gånger trillar man dit på ”off-by-one”-fel även som van utvecklare med många års erfarenhet.
E.W. Dijkstra har sagt mycket klokt och även i frågan om nollindexering så hade han en åsikt. I ”Why numbering should start at zero” så försvarar han tesen att man ska använda sig av nollindexering.
Mats Wiklander