[Tutor] How inefficient is this code?

Brian van den Broek brian.van.den.broek at gmail.com
Thu May 8 02:39:03 CEST 2014


On May 7, 2014 7:30 PM, "C Smith" <illusiontechniques at gmail.com> wrote:

<snip>

> Someone suggested projecteuler.net and I started blazing through
> things I had done before, when I realized this would be a good time to
> start more efficient practices instead of code that just happens to
> work and may be very inefficient.
>
> #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.

Intuitive judgements about efficiency and 5$ will buy you a Starbuck's.
That qualification made:

It is most likely to be more efficient to dispense with the results list.
Instead, move the parity test into the while loop and augment the running
sum there.

But, test the resultant code for efficiency or you only know that some guy
told you it was likely more efficient.

Best,

Brian vdB
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140507/30b277f9/attachment.html>


More information about the Tutor mailing list