Welcome to Project Lovelace! We're still in early development so there are still tons of bugs to find and improvements to make. If you have any suggestions, complaints, or comments please let us know on Discourse, Discord, or GitHub!

Molecular mass calculator

You will learn about: periodic table, reading files, and 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 code editor below 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 1

Input: Pa Output: 231.04

Example 2

Input: OCS Output: 60.08

Example 3

Input: C4H4AsH Output: 128.00

Example 4

Input: C20H25N3O Output: 323.44
 Difficulty  Timesink
 Function molecular_mass(chemical_formula)

You must be logged in to view your submissions.

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

Let us know what you think about this problem! Was it too hard? Difficult to understand? Also feel free to discuss the problem, ask questions, and post cool stuff on Discourse. You should be able see a discussion thread below. Would be nice if you don't post solutions in there but if you do then please organize and document your code well so others can learn from it.