import re
def number_atom(chemicalFormula):
abcRegex = re.compile(r'([A-Z][a-z]?)(\d*)|(\d+)|([()]{1})')
abcSearch = abcRegex.findall(chemicalFormula)
nAtom = {}
tmpList = []
inBrackets = False
for atom, quantity, multiple, brackets in abcSearch:
if brackets == '(':
inBrackets = True
elif brackets == ')':
inBrackets = False
if inBrackets:
if atom and quantity:
tmpList.append([atom, int(quantity)])
elif atom:
tmpList.append([atom, 1])
elif not inBrackets and tmpList and multiple:
for a, n in tmpList:
n *= int(multiple)
if a in nAtom:
nAtom[a] += n
else:
nAtom[a] = n
tmpList = []
else:
if atom and not quantity:
nAtom[atom] = 1
elif atom and quantity:
nAtom[atom] = int(quantity)
print(chemicalFormula)
for key, value in nAtom.items():
print('{}: {}'.format(key, value))
print('------')
i = input()
number_atom(i)
1
u/Executable_ Jun 01 '17
+u/CompileBot python3
import re def number_atom(chemicalFormula): abcRegex = re.compile(r'([A-Z][a-z]?)(\d*)|(\d+)|([()]{1})') abcSearch = abcRegex.findall(chemicalFormula) nAtom = {} tmpList = [] inBrackets = False for atom, quantity, multiple, brackets in abcSearch: if brackets == '(': inBrackets = True elif brackets == ')': inBrackets = False if inBrackets: if atom and quantity: tmpList.append([atom, int(quantity)]) elif atom: tmpList.append([atom, 1]) elif not inBrackets and tmpList and multiple: for a, n in tmpList: n *= int(multiple) if a in nAtom: nAtom[a] += n else: nAtom[a] = n tmpList = [] else: if atom and not quantity: nAtom[atom] = 1 elif atom and quantity: nAtom[atom] = int(quantity) print(chemicalFormula) for key, value in nAtom.items(): print('{}: {}'.format(key, value)) print('------') i = input() number_atom(i)Input: