[Tutor] parsing chemical formula

Tim Wilson wilson@chemsun.chem.umn.edu
Mon, 29 Mar 1999 09:51:44 -0600 (CST)


On Mon, 29 Mar 1999, Steve Spicklemire wrote:

Steve, thanks for the example. I'm still a little intimidated by the OOP
features that Python offers. I should probably just bit the bullet and dig
in and learn it. I think I understand how a list would be useful to store
the atoms until the total mass can be calculated. I don't see where you
parse the user input here. I'll be more specific: How will the program be
able to figure out how many atoms of each type are in a molecule like
(NH4)3PO4? How will it know the difference between CO (carbon monoxide)
and Co (a cobalt atom)? It seems to be that figuring out the difference
between Co and CO and interpreting the parentheses correctly is fairly
tricky (at least for me). Any other suggestions would be appreciated.

-Tim

Steve's sample code follows:
> # 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
> 
> 
> 
> 

--
Timothy D. Wilson			"A little song, a little dance,
University of MN, chem. dept.		a little seltzer down your 
wilson@chem.umn.edu			pants."   -Chuckles the Clown
Phone: (612) 625-9828                       as eulogized by Ted Baxter