You are given a string formula representing a chemical formula, along with a dictionary weights mapping each element symbol to its atomic weight. Return the total molecular weight of the formula.
A chemical formula consists of element symbols, optional digits, and optional parentheses:
-
An element symbol starts with an uppercase letter, optionally followed by one or more lowercase letters (for example
H
,
He
,
Mg
).
-
An element or a parenthesized group may be followed by a positive integer count. No count means a count of 1.
-
Parentheses
(
and
)
group sub-formulas, and a count after
)
multiplies the weight of the entire group.
You may assume every element appearing in formula has a corresponding entry in weights.
Function Signature
def molecular_weight(formula: str, weights: dict[str, int]) -> int:
Rules
-
Atomic weights are integers, and the answer is the integer sum of each atom's weight times the number of times it occurs once all counts and group multipliers are applied.
-
A count can have more than one digit (
C12
means 12 carbon atoms). Groups can be nested to any depth.
Constraints
-
1 <= len(formula) <= 1000
-
formula
consists of English letters, digits,
(
, and
)
.
-
formula
is always a valid chemical formula.
-
All element symbols follow the convention: one uppercase letter optionally followed by lowercase letters.
-
The total molecular weight fits in a 32-bit signed integer.
Examples
Input: formula = "H2O", weights = {"H": 1, "O": 16}
Output: 18
Two hydrogens weigh 2 * 1 = 2 and one oxygen weighs 16, so the total is 18.
Input: formula = "Mg(OH)2", weights = {"Mg": 24, "O": 16, "H": 1}
Output: 58
The group OH weighs 16 + 1 = 17 and appears twice, so the total is 24 + 2 * 17 = 58.
Input: formula = "K4(ON(SO3)2)2", weights = {"K": 39, "O": 16, "N": 14, "S": 32}
Output: 536
SO3 weighs 32 + 3 * 16 = 80, so ON(SO3)2 weighs 16 + 14 + 2 * 80 = 190. That group appears twice, giving 380, and K4 adds 4 * 39 = 156, for 536. Counting atoms instead gives 4 K, 14 O, 2 N and 4 S, which also sums to 536.