-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
726.py
108 lines (90 loc) · 3.19 KB
/
726.py
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
__________________________________________________________________________________________________
sample 24 ms submission
class Solution:
def countOfAtoms(self, formula: str) -> str:
stack, atom, dic, count, coeff, c = [], '', collections.defaultdict(int), 0, 1, 0
for i in formula[::-1]:
if i.isdigit():
count += int(i) * (10 ** c)
c += 1
elif i == ')':
stack.append(count)
coeff *= count
count = c = 0
elif i == '(':
coeff //= stack.pop()
count = c = 0
elif i.isupper():
atom += i
dic[atom[::-1]] += (count or 1) * coeff
atom = ''
count = c = 0
else:
atom += i
check = []
for atom in dic:
check.append((atom, dic[atom]))
check.sort(key=lambda x:x[0])
ans = ''
for atom, count in check:
ans += atom
if count > 1:
ans += str(count)
return ans
__________________________________________________________________________________________________
sample 13188 kb submission
class Solution:
def multiply(self,multiplier):
product=1
for c in multiplier:
product = product * c
return product
def sort_answer(self,dic):
output=[]
for key,val in sorted(dic.items()):
output.append(key)
if val==1:
continue
output.append(str(val))
return ''.join(output)
def countOfAtoms(self, formula: str) -> str:
from collections import defaultdict
multAr = []
parentheses=0
d=defaultdict(int)
element=None
elems=[]
num=None
i=len(formula)-1
while i>=0:
if formula[i].isdigit():
if i==len(formula)-1 or num==None:
num=formula[i]
else:
num= formula[i]+num
if formula[i].islower():
element = formula[i-1:i+1]
if num==None:
d[element]+= self.multiply(multAr)
else:
d[element]+=int(num) * self.multiply(multAr)
num=None
i-=2
elems.append(element)
continue
elif formula[i].isupper():
element=formula[i]
if num==None:
d[element]+= self.multiply(multAr)
else:
d[element]+=int(num) * self.multiply(multAr)
num=None
elems.append(element)
elif formula[i]==')':
multAr.append(int(num))
num=None
elif formula[i]=='(':
multAr.pop()
i-=1
return self.sort_answer(d)
__________________________________________________________________________________________________