1 hydrogen H 1.0079
if len(parts) == 4:
print float.parts[4]
else print 0 '%s does not have a well defined atomic weight.' % s(parts[3])
The elements in a list are numbered from 0 to length, so your list is [0]-->[3]. Since you didn't ask any questions, I have to assume that this is the problem.
if len(parts)==4:
print float(parts[3])
else :
print "no atomic weight for %s" % (parts[1])
## or
try:
a_weight = float(parts[3])
except:
print "no atomic weight for %s" % (parts[1])
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
Yeah, you're asking a parsing question: how do take a string representation of a chemical formula and represent it in memory?
I might do something like this, but there are smarter ways of doing it:
Z = 0
MASS = 1
NAME = 2
ELEMENTS = {'H': (1,1.00794,'hydrogen'),
'O': (8,15.9994,'oxygen'),
'C': (6,12.001, 'carbon'),
'N': (7,14.0064, 'nitrogen')}
def get_mass(symbol):
if symbol in ELEMENTS:
return ELEMENTS[symbol][MASS]
else:
raise ValueError, "Element not in table!"
def compute_mass(line):
mass = 0.0
tokens = line.split()
last = ''
for token in tokens:
# handle numbers
if token.isdigit():
# correct input: number follows valid element
if last:
mass += get_mass(last) * int(token)
last = ''
# incorrect input: number follows nothing at all, or other number
else:
raise SyntaxError, "Illegal formula!"
else:
# if element follows other element, add last to mass
if last:
mass += get_mass(last)
last = token
# done with the line; don't forget the tail!
if last:
mass += get_mass(last)
return mass
while True:
formula = raw_input("Enter a formula or 'quit': ")
if formula.lower() == 'quit':
break
else:
try:
m = compute_mass(formula)
print "mass is", m
except StandardError, e:
print e
So some explanations:
* The constants defined at the beginning let me extract elements without using obscure indices that can cause trouble if I forget to count from zero.
* The problem with parsing a formula like H 2 O is that I have to remember one token back. 2 whats? Oh, yeah, 2 H's. That's the role that 'last' plays in the compute_mass function. It has the effect of creating a small pipeline: we get the current token, but compute the mass of the last token.
* Doing it like this REQUIRES that we not forget the tail end.
* Handling formulas like diethyl ether, (C 2 H 5) 2 O, requires a stack for handling parentheses. If you feel adventurous, you can probably do it.
* I used try...except and raise to handle errors. If that's weird to you, then skip it.
Jeff
jrcagle
Practically a Master Poster
608 posts since Jul 2006
Reputation Points: 92
Solved Threads: 156