pythonize this!

Ian Kelly ian.g.kelly at gmail.com
Tue Jun 15 12:26:05 EDT 2010


On Tue, Jun 15, 2010 at 6:21 AM, Alain Ketterlin
<alain at dpt-info.u-strasbg.fr> wrote:
> 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

In fact, most of them are unnecessary:

from itertools import izip, cycle

def squares(start, stop):
    square = start * start
    step = start * 2 + 1
    for root in xrange(start, stop):
        yield square
        square += step
        step += 2

print sum(sign * square for sign, square in izip(cycle([1,1,1,-1,-1]),
squares(1, 2011)))

Now, anybody know how to make that version a one-liner without making
it go quadratic in run-time?

Cheers,
Ian



More information about the Python-list mailing list