pythonize this!

Ignacio Mondino ignacio.mondino at gmail.com
Tue Jun 15 20:13:18 EDT 2010


On Tue, Jun 15, 2010 at 8:49 AM, superpollo <utente at esempio.net> wrote:
> 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
> ...
>>>> print s
> 536926141
>>>>
>
> bye

I think This one is pretty, clean, using the standard library.
pretty pythonic.

def sign_and_sqr(n):
""" return a numbers square a change the sign accordingly
    if n % 5 == 0 or (n + 1) % 5 == 0:
        return  (n ** 2) * -1
    else:
        return n ** 2

result = sum([sign_and_sqr(x) for x in range(0,2011)])
print result

ok, the function has two exits, but im lazy at the moment :)


-- 
---------------------------------------------------------------------------

Ignacio Mondino
                                                               Don't Panic



More information about the Python-list mailing list