[Tutor] parsing chemical formula
Steve Spicklemire
steve@estel.uindy.edu
Mon, 29 Mar 1999 06:07:54 -0500 (EST)
I guess we're neglecting the mass defect due to the chemical
binding energy.
;-)
How about something like:
----------------------------------------------------------------------
# I'm making these up.... I really don't know the correct masses off the top...
#
ElementDict = {'H':1.0, 'He':4.0, 'Li':6.0, 'O':16.0 } # and on and on .....
class ElementContainer:
def __init__(self, name, count):
self.name = name
self.count = count
class Molecule:
elementList = None
massDefect = None # just in case we want to get fancy...
def addElement(self, name, count):
if self.elementList is None:
self.elementList = [] # a list allows multiple instances of ElementContainers
# with the same element...
self.elementList.append(ElementContainer(name, count))
def calcWeight(self):
weight = 0.0
for element in self.elementList:
weight = weight + element.count*ElementDict[element.name]
if self.massDefect is not None:
weight = weight - massDefect
return weight
if __name__=='__main__':
m = Molecule()
m.addElement('H',2)
m.addElement('O',1)
print "This damp example has a result of: ", m.calcWeight()
----------------------------------------------------------------------
-steve