Molecular Weight

Write a program that translates the molecular weight of a chemical compound of hydrogen, carbon, and oxygen, so that it can take as user input a chemical formula of the form C2H5OH for ethyl alcohol, COOHC6H4OCOCH3 or C9H804 for aspirin, CH3CH2CH2CH2CH2CH2CH2CH3 or C8H18 for octane, and so forth. You should write an algorithm to analyse an input string of this form, using string indexing as in section 3.1 to look at individual characters in the string. You should accumulate the total counts of hydrogen, carbon, and oxygen in the compound, and then use the formula in your previous section 2.11 assignment to compute the molecular weight

Enter a chemical formula, or just the enter key to quit: C2H5OH 
The molecular weight is 46.0688 
Enter a chemical formula, or just the enter key to quit: COOHC6H4OCOCH3
The molecular weight is 180.1598 
Enter a chemical formula, or just the enter key to quit: C9H804 
The molecular weight is 180.1598 
Enter a chemical formula, or just the enter key to quit: C8H18 
The molecular weight is 114.2302 
Enter a chemical formula, or enter key to quit:
def print_map(map):
    for element in map:
        print (str(element) + ": " + str(map[element]))

def calc_atomic_weight(map):
    tit
    for element in map:
        print (str(element) + ": " + str(mol_count[element]))
    print("The molecular weight is ")

# begin program
while True:

    # dictionary to store the occurances of molecular elements
    # the count of each element gets initialized to zero
    mol_count = { 'O':0, 'H':0, 'C':0 }
    number = "";

    user_in = input("Enter a chemical formula, or just the enter key to quit: ")

    # user string was empty
    # quit the program
    if (not user_in):
        break

    # otherwise begin analysis on the string
    i = 0
    while(i < len(user_in)):
        # we expect the first occurance to be a capital letter
        # of 'O' 'C' or 'H' *that is, exist within the dictionary*
        iter_char = user_in[i]
        if iter_char in mol_count:
            # the next occurance must either be another
            # character or a sequence of digits
            j = i + 1
            if(j < len(user_in) and user_in[j].isdigit()):
                while(j < len(user_in) and user_in[j].isdigit()):
                    number += user_in[j]
                    j += 1
                # continue where we left off
                i = j
            else:
                number = "1"
                i += 1
        else:
            print("Badly formed molecular formula; try again.")
            break

        # increment appropriate molecule
        mol_count[iter_char] += int(number)
        number = "";

    #print_map(mol_count)
    calc_atomic_weight(mol_count)

Last updated