Easy-Commented Python with Maths🐍
Code\npy\nclass Solution:\n    def countOfAtoms(self, f: str) -> str:\n        def isNumber(s):\n            for i in s:\n                if not i.isdigit():ret
# Code\n```py\nclass Solution:\n    def countOfAtoms(self, f: str) -> str:\n        def isNumber(s):\n            for i in s:\n                if not i.isdigit():return False\n            return True\n        \n        #Declarations of all used vars\n        arr,i,stack,ans,mp=[],0,[],"",{}\n        \n        #convert string to arr -> "Mg(OH)2" -> [\'Mg\', \'(\', \'O\', \'H\', \')\', \'2\'] \n        while i<len(f):\n            if f[i].isalpha():\n                temp=f[i]\n                i+=1\n                while i<len(f) and ord(f[i])>=ord(\'a\'):\n                    temp+=f[i]\n                    i+=1\n                i-=1\n                arr.append(temp)\n            elif isNumber(f[i]):\n                temp=f[i]\n                i+=1\n                while i<len(f) and ord(f[i])>=ord(\'0\') and ord(f[i])<=ord(\'9\'):\n                    temp+=f[i]\n                    i+=1\n                i-=1\n                arr.append(temp)\n            else:\n                arr.append(f[i])\n            i+=1\n\n        #stack to store the elements and their count \n        for i in range(len(arr)):\n            \n            #if numerical value found\n            \n            if isNumber(arr[i]):\n                val=int(arr[i])\n                \n            # if last index has \')\' iterate till \'(\' and multiply it with count \n            # else jusr muliply recent idx\n                \n                if arr[i-1]==\')\':\n                    l_idx=len(stack)-2\n                    while l_idx>0 and stack[l_idx][0]!=\'(\':\n                        stack[l_idx][1]*=val\n                        l_idx-=1\n                    stack[l_idx][0]=\'*\'\n                else:\n                    stack[-1][1]*=val\n            else:\n                stack.append([arr[i],1])\n                \n        #sort the stack for req ans\n        stack.sort()\n        \n        #check multiple occurance of Elements in stack [O,12, O,2] -> [O,14]\n        for i in stack:\n            if i[0] in mp:\n                mp[i[0]]+=i[1]\n            else:\n                mp[i[0]]=i[1]\n                \n        #dictonary to string\n        for i in mp:\n            if i in \'*()\':\n                continue\n            else:\n                ans+=i\n                if mp[i]!=1:\n                    ans+=str(mp[i])\n        return ans\n    \n    \n\\\n```
['Python3']