Accademia:Projecteuler 2.py

Versione del 15 mag 2011 alle 19:49 di Amos (discussione | contributi) (Creata pagina con '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, ....')
(diff) ← Versione meno recente | Versione attuale (diff) | Versione più recente → (diff)

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/env python3
import time
t = time.time() 

fibonacci = [1, 1]                       # potresti partire mettendo nella lista [1, 1]
next = fibonacci[-1] + fibonacci[-2]     # poi li sommi, ottieni 2
while next < 4000000:
    fibonacci.append(next)               # e con append lo aggiungi, ottenendo [1, 1, 2]
    next = fibonacci[-1] + fibonacci[-2] # poi sommi gli ultimi due [...]

sum_of_evens = 0
for number in fibonacci:
    if not number % 2:
        sum_of_evens += number

print(sum_of_evens)
                                                                                                                                             
print(time.time() - t)