1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| DIC = { 'H': 0, 'He': 1, 'Li': 2, 'C': 5, 'O': 7, 'S': 15, 'Al': 12, 'Cu': 29, }
RE_DIC = { 0: 'H', 1: 'He', 2: 'Li', 5: 'C', 7: 'O', 15: 'S', 12: 'Al', 29: 'Cu', }
def solve(s): stack = [[0] * 100] n = len(s) for idx, item in enumerate(s): if item.isupper():
end = idx + 1 while end <= n - 1 and s[end].islower(): end += 1 name = s[idx:end]
times = 1 if end <= n - 1 and s[end].isdecimal(): times = int(s[end]) stack[-1][DIC[name]] += times
elif item == '(': stack.append([0] * 100)
elif item == ')': times = 1 if idx != n - 1 and s[idx + 1].isdecimal(): times = int(s[idx + 1]) popped = stack.pop() for i in range(len(popped)): stack[-1][i] += popped[i] * times
return stack
if __name__ == '__main__': s = "Cu2(OH)2CO3" ret = solve(s) for i in range(100): if ret[0][i] != 0: print(f"原子{RE_DIC[i]} : {ret[0][i]}")
|