The following Python code works correctly; but I can't help but wonder if 
my for loop is better implemented as something else: a list comprehension 
or something else more Pythonic.

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)
--------------------

Example use:

--------------------
w1 = Water(50,0)
w2 = Water(50,100)
w3 = Water(25,50)

print CombineWater((w1,w2,w3))
--------------------

prints, as expected: 125.00, 50.00



_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to