Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Newbie to python. Very newbie question

Reply
Thread Tools

Re: Newbie to python. Very newbie question

 
 
rusi
Guest
Posts: n/a
 
      04-07-2013
On Apr 7, 4:16?pm, ReviewBoard User <(E-Mail Removed)>
wrote:
> 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 am new to Python and am also looking for good documentation on
> python functions.http://www.python.org/doc/does not provide examples
> of usage of each function


In problems like this it is usually preferable to use list
comprehensions over map/filter.
Your problem is literally solvable like this:

>>> [sq for sq in [x*x for x in range(100)] if sq%2 == 1 and sq <= 100]

[1, 9, 25, 49, 81]
>>> sum([sq for sq in [x*x for x in range(100)] if sq%2 == 1 and sq <= 100])

165

Using Dave's observation that odd(x) == odd(x*x) it simplifies to
>>> sum([x*x for x in range(100) if x%2==1 and x*x <=100])

165

Note: Python comprehensions unlike Haskell does not allow local lets
so the x*x has to be repeated
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Very very very basic question Peter C Programming 14 02-14-2005 09:46 AM
very very very long integer shanx__=|;- C Programming 19 10-19-2004 03:55 PM
very very very long integer Abhishek Jha C Programming 4 10-17-2004 08:19 AM
Quick Book file access very very very slow Thomas Reed Computer Support 7 04-09-2004 08:09 PM
very Very VERY dumb Question About The new Set( ) 's Raymond Arthur St. Marie II of III Python 4 07-27-2003 12:09 AM



Advertisments