Newbie to python. Very newbie question

Ian Foote ian at feete.org
Sun Apr 7 15:23:49 EDT 2013


On 07/04/13 20:09, Dennis Lee Bieber wrote:
> On Sun, 7 Apr 2013 04:16:27 -0700 (PDT), ReviewBoard User
> <lalitha.viswanath at gmail.com> declaimed the following in
> gmane.comp.python.general:
>
>> Hi
>> I am a newbie to python and am trying to write a program that does a
>> sum of squares of numbers whose squares are odd.
>> For example, for x from 1 to 100, it generates 165 as an output (sum
>> of 1,9,25,49,81)
>>
>> Here is the code I have
>> print reduce(lambda x, y: x+y, filter(lambda x: x%2, map(lambda x:
>> x*x, xrange
>> (10**6)))) = sum(x*x for x in xrange(1, 10**6, 2))
>>
>> I am getting a syntax error.
>> Can you let me know what the error is?
>>
> 	I can't even read that mess... three nested lambda?
>
> 	Not the most efficient version but...
>
>>>> sum( x*x for x in range(100/2) if (x*x % 2) and (x*x < 100) )
> 165
>>
>
> 	The range(100/2) is a simple reduction to avoid invoking a sqrt
> function... the more economical is
>
>>>> import math
>>>> sum( x*x for x in range(int(math.sqrt(100))) if x*x % 2)
> 165
>>>>

I'm surprised no one has suggested:

 >>> import math
 >>> sum( x*x for x in range(1, int(math.sqrt(100)), 2))

Regards,
Ian F




More information about the Python-list mailing list