Alright, So I am rather new to programming and Python and I had a couple of questions that maybe you guys could help me with...

I currently have a .txt that when read in Python is a list, now i want to be able to split it up into seperate components so that i can put them all in a dictionary. I want to be able to up one part of the line and have it give me another part (obviously the purpose of having it as a dictionary).

a sample line from the file:

1 hydrogen H 1.0079

So if i were to say

>>>Print weight
1.0079

Here is a partial look at the code that I was attempting to write:

def make_atomic_weights_dict(data_lines):
d = {}
for data_line in data_lines:
parts = data_line.split()
d'[parts[3]] = float.parts [4]'  # these will be added to dictionary
if len(parts) == 4:
print float.parts[4]
else print 0 '%s does not have a well defined atomic weight.' % s(parts[3])

Thanks a bunch

Edited 3 Years Ago by happygeek: fixed formatting

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

Alright, well I solved my previous problem...My next issue, is I want to be able to add up the numbers from the dictionary...how would I go about doing that?

So say I want to calculate the atomic mass of H2O I want to be able to type:

>>>print molecular_weight( 'H 2 O', atomic_weights)

some # comes out

I don't need a whole solution, just where would be a good place to start looking

Ok, so should I use if statements? because 'H 2 O' will be a string, and I want to relate each individual part to my previous dictionary...

If H is in atomic_weights
print #
2
false

therefore 2*H, etc...

Would that work?

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

Ok, well I read what you gave me and I kind of put some stuff to work on my own...The beginning lines may not make sense because they relate to other parts of the code

def molecular_weight(formula, atomic_weights):
    weights = []
    formula_parts = formula.split()
    for parts in formula_parts:
        if parts in atomic_weights:
            weights.append(atomic_weights.itervalues())
        elif 0 in atomic_weights:
            print '%s does not have well-defined atomic weight' % (formula_parts)
        elif parts in formula_parts.isdigits(n): # isdigit doesn't seem to be a proper command what should I use instead....
            weights[-1] *= n # I want to be able to append this to weights, but i get an syntax error when trying to use the .append function
    return sum(weights)
This article has been dead for over six months. Start a new discussion instead.