fork download
  1. import sys
  2.  
  3. def get_symb(i, string):
  4. symbol = ''
  5. if string[i].isupper():
  6. symbol += string[i]
  7. i += 1
  8. if i < len(string) and string[i].islower():
  9. symbol += string[i]
  10. i += 1
  11. return (i, symbol)
  12.  
  13. def get_mult(i, string):
  14. mult = 0
  15. while i < len(string) and string[i].isdigit():
  16. mult = mult * 10 + int(string[i])
  17. i += 1
  18. return (i, 1) if not mult else (i, mult)
  19.  
  20. def parse(index, string):
  21. counts = {}
  22. def update_counts(dct, mult):
  23. for s in dct:
  24. if s in counts: counts[s] += dct[s] * mult
  25. else: counts[s] = dct[s] * mult
  26.  
  27. while index < len(string):
  28. if string[index] == ')':
  29. return (index+1,counts)
  30. elif string[index]=='(':
  31. index,grp_cnts = parse(index+1, string)
  32. index,grp_cnt = get_mult(index, string)
  33. update_counts(grp_cnts, grp_cnt)
  34. else:
  35. index,symbol = get_symb(index, string)
  36. index,count = get_mult(index, string)
  37. update_counts({symbol:count}, 1)
  38. return counts
  39.  
  40. if __name__ == '__main__':
  41. for line in sys.stdin:
  42. result = parse(0,line.strip())
  43. for sym,mult in sorted(result.items()):
  44. print('{}: {}'.format(sym, mult))
  45. print()
Success #stdin #stdout 0s 23352KB
stdin
C6H12O6 
CCl2F2
NaHCO3
C4H8(OH)2
PbCl(NH3)2(COOH)2
stdout
C: 6
H: 12
O: 6
()
C: 1
Cl: 2
F: 2
()
C: 1
H: 1
Na: 1
O: 3
()
C: 4
H: 10
O: 2
()
C: 2
Cl: 1
H: 8
N: 2
O: 4
Pb: 1
()