pythonize this!
Boris Borcic
bborcic at gmail.com
Wed Jun 16 11:31:51 EDT 2010
Ignacio Mondino wrote:
> 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:
imho this fails DRY too much to be wholly pythonic,
write rather
if n%5 in (0,4) :
> 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 :)
>
>
More information about the Python-list
mailing list