pythonize this!

Stefan Behnel stefan_ml at behnel.de
Tue Jun 15 08:23:23 EDT 2010


superpollo, 15.06.2010 13:49:
> goal (from e.c.m.): evaluate
> 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three
> consecutive + must be followed by two - (^ meaning ** in this context)
>
> my solution:
>
>  >>> s = 0
>  >>> for i in range(1, 2011):
> ... s += i**2
> ... if not (i+1)%5:
> ... s -= 2*i**2
> ... if not i%5:
> ... s -= 2*i**2

Pretty ugly, if you ask me. What about this:

     s = 0
     for i in range(1, 2011):
         if i%5 in (1,2,3):
             s += i**2
         else:
             s -= i**2

Here's the obvious one-liner:

     s = sum(i**2 if i%5 in (1,2,3) else -i**2
             for i in range(1, 2011))

Runs in ~600 usecs for me according to timeit - pretty fast.

Stefan




More information about the Python-list mailing list