-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathParsing A Boolean Expression.py
69 lines (53 loc) · 2.32 KB
/
Parsing A Boolean Expression.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
class Solution:
def parseBoolExpr(self, expression: str) -> bool:
# expresssion map
opMap = {"!" : "!", "|" : "|" , "&" : "&"}
expMap = {"t" : True, "f" : False}
expStack = []
opStack = []
ans = 0
i = 0
while i < len(expression):
if expression[i] in opMap:
opStack.append(opMap[expression[i]])
elif expression[i] in expMap:
expStack.append(expMap[expression[i]])
elif expression[i] == "(":
expStack.append("(")
# strat performing operations
elif expression[i] == ")":
op = opStack.pop()
ans = [] # evaluator arr
# To Check
# print("EXPSTACK :- ", expStack, "OPSTACK :- ", opStack, "outer WHILE")
# Performing serries of operation on exp inside a ()
while expStack[-1] != "(":
# To check
# print("EXPSTACK :- ", expStack, "OPSTACK :- ", opStack, "OPerator :- ",op, "INNER WHILE")
# Not single operation only
if op == "!":
ans.append(not expStack.pop())
else:
ans.append(expStack.pop())
# Operation evaluation for more then 1 exp inside () for &, or
while len(ans) > 1:
# or
if op == "|":
exp1, exp2 = ans.pop(), ans.pop()
res = exp1 or exp2
ans.append(res)
# and
elif op == "&":
exp1, exp2 = ans.pop(), ans.pop()
res = exp1 and exp2
ans.append(res)
# poping ")" and adding the res of operation done above
expStack.pop() # poping ")"
expStack.append(ans[-1])
# increment i
i += 1
return expStack[-1]
"""
TC : O(n * m) | n = len(expression), m = no of expression inside a prenthesis
Sc : O(n)
"""