From: superpollo on
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
From: Ulrich Eckhardt on
superpollo wrote:
> ... s += i**2
> ... if not (i+1)%5:
> ... s -= 2*i**2
> ... if not i%5:
> ... s -= 2*i**2

if not (i % 5) in [1, 2]:
s += i**2
else:
s -= i**2

Untested code.

Uli

--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

From: Alain Ketterlin on
superpollo <utente(a)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.
From: superpollo on
Ulrich Eckhardt ha scritto:
> superpollo wrote:
>> ... s += i**2
>> ... if not (i+1)%5:
>> ... s -= 2*i**2
>> ... if not i%5:
>> ... s -= 2*i**2
>
> if not (i % 5) in [1, 2]:
> s += i**2
> else:
> s -= i**2
>
> Untested code.

does not work:

>>> s = 0
>>> for i in range(1, 2011):
.... if not (i % 5) in [1, 2]:
.... s += i**2
.... else:
.... s -= i**2
....
>>> print s
546627205
>>>

but this does:

>>> s = 0
>>> for i in range(1, 2011):
.... if i % 5 in [1, 2, 3]:
.... s += i**2
.... else:
.... s -= i**2
....
>>> print s
536926141

bye
From: Stefan Behnel on
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