#K15826. Count Atoms in a Chemical Formula

    ID: 24443 Type: Default 1000ms 256MiB

Count Atoms in a Chemical Formula

Count Atoms in a Chemical Formula

Given a chemical formula as a string, count and report the number of atoms of each element present in the formula.

The chemical formula may contain elements with one or two letter symbols, numbers indicating multiplicity, and nested parentheses. For example, the formula was described by the following examples:

  • \(H_2O\) should output {'H': 2, 'O': 1}.
  • \(Mg(OH)_2\) should output {'H': 2, 'Mg': 1, 'O': 2}.
  • \(K_4(ON(SO_3)_2)_2\) should output {'K': 4, 'N': 2, 'O': 14, 'S': 4}.

Your task is to implement a function that parses such a formula string and outputs a dictionary (or equivalent in your language) with the atom counts. The output should list the elements in lexicographical order using single quotes around the keys and exactly following the format shown in the examples.

inputFormat

The input is a single line containing the chemical formula as a string.

For example:

H2O

outputFormat

Output a single line: a dictionary-like string representation of the atom counts with keys sorted lexicographically. The output format should be exactly as shown in the examples.

For example:

{'H': 2, 'O': 1}
## sample
H2O
{'H': 2, 'O': 1}