Parsing a Chemistry Formula in Python
问题 I am trying to solve this problem: https://leetcode.com/articles/number-of-atoms/#approach-1-recursion-accepted. The question is: given a formula like C(Mg2(OH)4)2 , return a hash table with elements and their counts. Element names always start with a capital letter and may be followed by a small letter. I thought that I will first start by solving the simplest case: no brackets. def bracket_hash(formula): element = "" atom_count = 0 element_hash = {} for x in formula: if x.isupper(): if