Molecular mass calculator

Useful to know: reading files, text parsing.

Molecules are made up of atoms, so to calculate the mass of a molecule you just add up the masses of the atoms but each atom has a different mass.Atoms are so light that using grams to describe their mass is pretty annoying so we use other units like the atomic mass unit (amu). 1 amu is defined as one twelevth the mass of a carbon-12 atom, or $1.661 \times 10^{-27} \; \mathrm{kg}$. For example, water (H2O) is a molecule made up of two hydrogens and an oxygen. The hydrogen (H) atoms have a mass of 1.008 amu while carbon (C) has a mass of 12.011 amu and the heaviest atom on the periodic table, Oganesson (Og), has a mass of 294 amu while a methane molecule (CH4) has a mass of 16.04 amu.

A bunch of different molecules: trinitrotoluene or TNT (C7H5N3O6), ethanol (C2H5OH), water (H2O), chloroform (CHCl3), and adenosine triphosphate or ATP (C10H16N5O13P3). An example calculation is shown for methane (CH4). The atoms are colored according to the CPK coloring convention so hydrogen atoms are white, carbon is gray, nitrogen is blue, oxygen is red, chlorine is green, and phosphorus is orange.

Given the chemical formula of a molecule, return its mass in amu. You might find periodic_table.csv useful. It's a comma-separated file containing all the elements from the periodic table and their masses in amu. The starter code in the submissions tab shows how you can read the data from the file and store it in a dictionary in Python.

Input: The molecule's chemical formula.

Output: The molecule's mass in atomic mass units (amu).

Example input


Example output


You must be logged in to submit code but you can play around with the editor.

You must be logged in to upload code.

  • Would be good to include the regex in post-problem notes.