return reduce(lambda x, y: x.grade+y.grade, self.reviews)

Discussion in 'Python' started by cnb, Aug 29, 2008.

  1. cnb

    cnb Guest

    class Customer(object):
    def __init__(self, idnumber, review):
    self.idnumber = idnumber
    self.reviews = [review]

    def addReview(self, review):
    self.reviews.append(review)

    def averageGrade(self):
    tot = 0
    for review in self.reviews:
    tot += review.grade
    return tot / len(self.reviews)

    def av_grade(self):
    return reduce(lambda x, y: x.grade+y.grade, self.reviews)


    now,the function is pointless and incorrect but av_grade doesn't work.
    why can't i use reduce like this?
     
    cnb, Aug 29, 2008
    #1
    1. Advertising

  2. On Aug 29, 1:54 pm, cnb <> wrote:
    > class Customer(object):
    > def __init__(self, idnumber, review):
    > self.idnumber = idnumber
    > self.reviews = [review]
    >
    > def addReview(self, review):
    > self.reviews.append(review)
    >
    > def averageGrade(self):
    > tot = 0
    > for review in self.reviews:
    > tot += review.grade
    > return tot / len(self.reviews)
    >
    > def av_grade(self):
    > return reduce(lambda x, y: x.grade+y.grade, self.reviews)
    >
    > now,the function is pointless and incorrect but av_grade doesn't work.
    > why can't i use reduce like this?


    Because in reduce's lambda, 'x' is the result accumulated so far and
    'y' is the next element in the iterable. In this case, after you have
    consumed the first two reviews, 'x' is a number (the sum of the first
    two grades) and 'y' is the third review, so you're trying to add a
    number to a review and you get an error. As a rule of thumb, never use
    reduce(); it's rarely useful and can always be written out explicitly
    as a loop.

    What you want can be expressed much easier and efficiently with a
    generator expression as:

    def av_grade(self):
    # XXX: missing 0 reviews handling
    return sum(review.grade for review in self.reviews) /
    len(self.reviews)

    HTH,
    George
     
    George Sakkis, Aug 29, 2008
    #2
    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. Sims
    Replies:
    1
    Views:
    416
    Kim André Akerø
    May 6, 2004
  2. Ralf W. Grosse-Kunstleve
    Replies:
    16
    Views:
    622
    Lonnie Princehouse
    Jul 11, 2005
  3. Ralf W. Grosse-Kunstleve
    Replies:
    18
    Views:
    623
    Bengt Richter
    Jul 11, 2005
  4. Ralf W. Grosse-Kunstleve
    Replies:
    2
    Views:
    430
    Dan Sommers
    Jul 12, 2005
  5. falcon
    Replies:
    0
    Views:
    404
    falcon
    Jul 31, 2005
Loading...

Share This Page