From: Jussi Piitulainen on 15 Jun 2010 08:35 superpollo 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 > ... > >>> print s > 536926141 > >>> > > bye Me two: s = 0 for k in range(1, 2010, 5): s += k**2 + (k + 1)**2 + (k + 2)**2 - (k + 3)**2 - (k + 4)**2 s = 0 for k in range(1, 2011): s += k**2 * (-1 if k % 5 in {4,0} else +1) From: Peter Otten on 15 Jun 2010 08:37 superpollo 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) >>> from itertools import cycle, izip >>> sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) 536926141 From: superpollo on 15 Jun 2010 08:55 Peter Otten ha scritto:> superpollo 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) > >>>> from itertools import cycle, izip >>>> sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) > 536926141 don't understand it bit i like this a lot! From: superpollo on 15 Jun 2010 08:55 superpollo ha scritto:> Peter Otten ha scritto: >> superpollo 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) >> >>>>> from itertools import cycle, izip >>>>> sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) >> 536926141 > > don't understand it bit i like this a lot! ^^^ *but* From: Stefan Behnel on 15 Jun 2010 09:01 Stefan Behnel, 15.06.2010 14:23:> 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. Just for the record, this Cython code runs in ~15 usecs for me: def makesum(): return sum(i**2 if i%5 in (1,2,3) else -i**2 for i in range(1, 2011)) using the latest Cython 0.13pre. The "" cast is required to drop the sum() into efficient C code. Without it, the code runs in 55 usecs. Stefan First  |  Prev  |  Next  |  Last