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

Max Noel maxnoel_fr at yahoo.fr
Wed Jan 26 04:39:28 CET 2005


On Jan 26, 2005, at 03:17, 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.
>
> Comments?
>
> The point of the code is to take a sequence of objects, each object
> representing an amount of water with a given mass and temperature, and 
> to
> return another object that represents all the water ideally combined.  
> The
> formulae for the combined mass and temp are respectively:
>
>  combined mass = M1 + M2 + M3  (duh)
>  combined temp = ((M1*T1) + (M2*T2) + (M3*T3)) / (M1 + M2 + M3)
>
> Here's my code:
> --------------------
> class Water:
>     def __init__(self, WaterMass, WaterTemperature):
>         self.mass = WaterMass
>         self.temperature = WaterTemperature
>     def __repr__(self):
>         return ("%.2f, %.2f" % (self.mass, self.temperature))
>
> def CombineWater(WaterList):
>     totalmass=0
>     numerator = 0; denominator = 0
>     for WaterObject in WaterList:
>         totalmass += WaterObject.mass
>         numerator += WaterObject.mass * WaterObject.temperature
>     return Water(totalmass, numerator/totalmass)

	Well, you can do this with list comprehensions, yeah:

totalmass = sum([WaterObject.mass for WaterObject in WaterList])
totaltemp = sum([WaterObject.mass * WaterObject.temp for WaterObject in 
WaterList]) / totalmass
return Water(totalmass, totaltemp)


	Doesn't seem that much more Pythonic to me. I find it about as 
readable as your code, but someone who isn't used to list 
comprehensions will find that weird-looking. However, someone who uses 
functional programming languages a lot (Lisp, Scheme, Haskell, ML...) 
will be familiar with that.

	The actual pros of that method is that it's a functional approach and 
that it has less lines than your approach (you can even reduce it to a 
one-liner by adding a third list comprehension, but at that point it 
starts to look ugly).
	As for the cons, as I said, it may seem less readable than the 
original version to the non-experienced; and chances are it's slower 
than the original version since it has to iterate through 4 lists 
instead of 2.

	In any case, when in doubt, do what you think will be easier to 
maintain.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"



More information about the Tutor mailing list