Clean Python Lexer/Parser


  • 0
    J
        def countOfAtoms(self, formula):
            ts = re.findall('[A-Z][a-z]*|\d+|[()]', formula)
            
            global j
            j = 0
            
            def ca():
                global j
                if j == len(ts) or ts[j] == ')':
                    return collections.defaultdict(int)
                if ts[j] == '(':
                    j += 1; r = ca(); j += 1
                    if j < len(ts) and re.match('\d+', ts[j]):
                        for e in r:
                            r[e] *= int(ts[j])
                        j += 1                    
                            
                    r2 = ca()
                    for k in r2:
                        r[k] += r2[k]
                    return r
                        
                e = ts[j]; j += 1
                if j < len(ts) and re.match('\d+', ts[j]):
                    c = int(ts[j]); j += 1
                else:
                    c = 1
                r = ca()
                r[e] += c
                return r
            r = ca()
            s = ''
            for k in sorted(r.keys()):
                s += k + ('' if r[k] == 1 else str(r[k]))
            
            return s
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.