I remember that when I was in high school we used to have a lot of chemistry classes filled with problem solving. The key part of them was to calculate molar masses of different molecules. That segment, although essential, was rather boring. So I always wanted to have something that would speed up the calculations for me.
This time your job is to write a solver that will calculate a molar mass of a chemical formula. Make sure your solution works by using it on the following input:
Below I paste the formulas and their masses for testing purposes.
formulas = ["CH4", "H2O", "HCl", "CO2", "C3H8", "C2H5OH", "(CH3)2CO",
"NaCl", "CH3COOH", "H2CO3", "C6H12O6", "C11H12N2O2",
"CH3(CH2)14COOH", "C34H32O4N4Fe", "Ca10(PO4)6(OH)2",
"C169719H270466N45688O52238S911"]
masses = [16.043, 18.01528, 36.46, 44.01, 44.097, 46.069, 58.08, 58.443,
60.052, 62.03, 180.156, 204.229, 256.43, 616.487, 1004.61,
3_816_030]
A list of chemical elements and their masses is to be found, e.g. on this Wikipedia page.
For simplicity, you may assume, that a chemical formula (at least the one at a high school level) is composed of ASCII characters (capital/small letters + digits) and non-nested brackets.