-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fd75800
commit e22662d
Showing
2 changed files
with
38 additions
and
2 deletions.
There are no files selected for viewing
36 changes: 36 additions & 0 deletions
36
2024-10-October-LeetCoding-Challenge/Parsing A Boolean Expression.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
class Solution: | ||
BOOL_MAP = {'t': True, 'f': False} | ||
|
||
def parseBoolExpr(self, expression: str) -> bool: | ||
stack = list() | ||
for ch in expression: | ||
if ch == ')': | ||
vals = set() | ||
while stack[-1] != '(': | ||
vals.add(stack.pop()) | ||
stack.pop() | ||
operation = stack.pop() | ||
if operation == '&': | ||
stack.append(all(vals)) | ||
elif operation == '|': | ||
stack.append(any(vals)) | ||
else: | ||
stack.append(not vals.pop()) | ||
elif ch != ',': | ||
stack.append(self.BOOL_MAP.get(ch, ch)) | ||
return stack.pop() | ||
|
||
|
||
def main(): | ||
expression = '&(|(f))' | ||
assert Solution().parseBoolExpr(expression) is False | ||
|
||
expression = '|(f,f,f,t)' | ||
assert Solution().parseBoolExpr(expression) is True | ||
|
||
expression = '!(&(f,t))' | ||
assert Solution().parseBoolExpr(expression) is True | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters