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

C

cnb

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?
 
G

George Sakkis

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top