On 2014-05-07 16:27, C Smith wrote:

#sum all even fib seq integers under 4 million
fibs = [1,2]
sum = 0
while fibs[-1] < 4000000:
    nexty = fibs[-1] + fibs[-2]
    fibs.append(nexty)

for xer in fibs:
    if xer%2 == 0:
        sum += xer
print sum

This gets the correct solution, but what would be ways to improve
speed or use more complicated parts of Python to do the same thing.
Thanks in advance

I think you could eliminate the second part, could you not, by inserting the (slightly modified) if statement into the while statement?
while fibs[-1] < 4000000:
    nexty = fibs[-1] + fibs[-2]
    if nexty%2 ==0:
        sum += nexty
    fibs.append(nexty)

Also you might want to initialize 'sum' to 1 rather than 0 since the second element in your 'fibs' won't get counted.


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to