Your task is when given a chemical formula as input, output the total number of atoms in the formula.
Input
A chemical formula in any reasonable format. Each chemical formula has the following:
- A leading coefficient, which is a number \$N > 1\$.
- At least 0 groupings of elements surrounded by parentheses.
- Groupings can have both elements and groupings inside of them.
- At least 1 element.
- Elements match the regex
[A-Z][a-z]*
.
- Elements match the regex
- Each grouping and element can have an optional subscript, which is an
_
followed by a number \$N > 1\$
Output
The total number of atoms in the formula. Rules for counting are as follows:
- A coefficient before the formula multiplies the total count that many times.
- A subscript multiples the group or atom it follows that many times.
- An element with no coefficient or subscript represents 1 atom.
Testcases
In -> Out (Notes)
H_2O -> 3
CO_2 -> 3
Co_2 -> 2 (2 cobalts)
3 C_2H -> 9
EeeEeuEetUue -> 4
3 (C_21H_30O_2)_3 -> 477 (= 3 * (53) * 3)
32H -> 32
C_10H_16N_5O_13P_3 -> 47
(Ga(U(Y_2)_3)_4)_5 -> 145 (= (1 + (1 + (2 * 3)) * 4) * 5)
Ti(Ca_2(HSO_4)_2)_2 -> 29 (= 1 + (2 + (1 + 1 + 4) * 2) * 2))
This is code-golf, so shortest code wins!