1linktotal = 0
2linkfor n in four_million_sequence:
3link if n % 2 == 0:
4link total += n
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:
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
1linkdef generate_fibonacci_sequence(term_limit, first_term, second_term):
2link sequence = [first_term, second_term]
3link while True:
4link next_number = sequence[-1] + sequence[-2]
5link if next_number < term_limit:
6link sequence.append(next_number)
7link else:
8link break
9link
10link return sequence
11link
12linkfour_million_sequence = generate_fibonacci_sequence(4000000, 1, 2)
13linkprint(sum([n for n in four_million_sequence if n % 2 == 0])) # // @see [List Comprehension](https://www.programiz.com/python-programming/list-comprehension)
term_limit
: the maximum number in the sequencefirst_term
: the first number in the sequencesecond_term
: the second number in the sequencesequence
next_number
reaches the term_limit
.sequence[-1]
and sequence[-2]
respectively.next_number
is less than the term_limit
. 1linkprint(generate_fibonacci_sequence(10, 0, 1))
2link[0, 1, 1, 2, 3, 5, 8]
1linkprint(generate_fibonacci_sequence(90, 1, 2))
2link[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
1linktotal = 0
2linkfor n in four_million_sequence:
3link if n % 2 == 0:
4link total += n
4613732