Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   return reduce(lambda x, y: x.grade+y.grade, self.reviews) (http://www.velocityreviews.com/forums/t632945-return-reduce-lambda-x-y-x-grade-y-grade-self-reviews.html)

cnb 08-29-2008 05:54 PM

return reduce(lambda x, y: x.grade+y.grade, self.reviews)
 
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?

George Sakkis 08-29-2008 06:20 PM

Re: return reduce(lambda x, y: x.grade+y.grade, self.reviews)
 
On Aug 29, 1:54 pm, cnb <circularf...@yahoo.se> 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


All times are GMT. The time now is 12:55 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.