pythonize this!
Alain Ketterlin
alain at dpt-info.u-strasbg.fr
Tue Jun 15 08:21:49 EDT 2010
superpollo <utente at esempio.net> writes:
> 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
You compute i**2 too many times (7/5 times more than necessary) and
twice too many modulos. I suggest:
c = { 0:1, 1:1, 2:1, 3:-1, 4:-1 }
#or, why not: c = lambda i : +1 if (i%5) < 3 else -1
s = 0
for i in range(1,2011):
s += c[(i-1)%5]*(i**2)
print s
Or, as a one liner using a list comprehension:
print sum( ( c[(i-1)%5]*i**2 for i in xrange(1,2011) ) )
I don't know which one is the fastest (between dict+loop, dict+compr,
lambda+loop and lambda+compr).
-- Alain.
More information about the Python-list
mailing list