[Tutor] Should this be a list comprehension or something?

Sean Perry shaleh at speakeasy.net
Thu Jan 27 08:13:04 CET 2005


Terry Carroll wrote:
  > My goal here is not efficiency of the code, but efficiency in my Python
> thinking; so I'll be thinking, for example, "ah, this should be a list 
> comprehension" instead of a knee-jerk reaction to use a for loop.
> 

as Alan says, list comprehensions, like map should be used to generate
new lists. What you should have thought was -- hmm, this looks like a
job for reduce!

def sumWater(w1, w2):
     total_mass = w1.mass + w2.mass
     numerator = (w1.mass * w1.temperature) + (w2.mass * w2.temperature)
     return Water(total_mass, numerator / total_mass)

def CombineWater(WaterList):
     return reduce(sumWater, WaterList)

if __name__ == '__main__':
     w1 = Water(50,0)
     w2 = Water(50,100)
     w3 = Water(25,50)

     print CombineWater2((w1,w2,w3))

Now, the sum_water function could also be folded into the Water class as
an __add__ method if you like as someone else suggested.

See, the problem with your old code was that the list walking and the
summation were done by the same code. By pulling sumWater out you can
test it separately. You could also pass different functions to CombineWater.

And now, for the pedant in me. I would recommend against naming
functions with initial capital letters. In many languages, this implies
a new type (like your Water class). so CombineWater should be combineWater.



More information about the Tutor mailing list