fork download
  1. import re
  2.  
  3. def number_atom(chemicalFormula):
  4. abcRegex = re.compile(r'([A-Z][a-z]?)(\d*)|(\d+)|([()]{1})')
  5. abcSearch = abcRegex.findall(chemicalFormula)
  6. nAtom = {}
  7. tmpList = []
  8. inBrackets = False
  9. for atom, quantity, multiple, brackets in abcSearch:
  10. if brackets == '(':
  11. inBrackets = True
  12. elif brackets == ')':
  13. inBrackets = False
  14.  
  15. if inBrackets:
  16. if atom and quantity:
  17. tmpList.append([atom, int(quantity)])
  18. elif atom:
  19. tmpList.append([atom, 1])
  20. elif not inBrackets and tmpList and multiple:
  21. for a, n in tmpList:
  22. n *= int(multiple)
  23. if a in nAtom:
  24. nAtom[a] += n
  25. else:
  26. nAtom[a] = n
  27. tmpList = []
  28. else:
  29. if atom and not quantity:
  30. nAtom[atom] = 1
  31. elif atom and quantity:
  32. nAtom[atom] = int(quantity)
  33.  
  34. print(chemicalFormula)
  35. for key, value in nAtom.items():
  36. print('{}: {}'.format(key, value))
  37. print('------')
  38.  
  39. i = input()
  40. number_atom(i)
Success #stdin #stdout 0.02s 28384KB
stdin
C6H12O6
CCl2F2
NaHCO3
C4H8(OH)2
PbCl(NH3)2(COOH)2
stdout
C6H12O6
O: 6
C: 6
H: 12
------