Re: Newbie to python. Very newbie question

Discussion in 'Python' started by rusi, Apr 7, 2013.

  1. rusi

    rusi Guest

    On Apr 7, 4:16?pm, ReviewBoard User <>
    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
     
    rusi, Apr 7, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Raymond Arthur St. Marie II of III

    very Very VERY dumb Question About The new Set( ) 's

    Raymond Arthur St. Marie II of III, Jul 23, 2003, in forum: Python
    Replies:
    4
    Views:
    518
    Raymond Hettinger
    Jul 27, 2003
  2. shanx__=|;-

    very very very long integer

    shanx__=|;-, Oct 16, 2004, in forum: C Programming
    Replies:
    19
    Views:
    1,718
    Merrill & Michele
    Oct 19, 2004
  3. Abhishek Jha

    very very very long integer

    Abhishek Jha, Oct 16, 2004, in forum: C Programming
    Replies:
    4
    Views:
    467
    jacob navia
    Oct 17, 2004
  4. Peter

    Very very very basic question

    Peter, Feb 8, 2005, in forum: C Programming
    Replies:
    14
    Views:
    542
    Dave Thompson
    Feb 14, 2005
  5. olivier.melcher

    Help running a very very very simple code

    olivier.melcher, May 12, 2008, in forum: Java
    Replies:
    8
    Views:
    2,376
Loading...

Share This Page