Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to evaluate Boolean expression from a string in Python?
Boolean expressions in strings can be evaluated by parsing the tokens and using a stack to handle operator precedence and parentheses. This approach splits the expression into components and processes them systematically.
Problem Statement
Given a string containing a boolean expression with operators "and" and "or", we need to evaluate it and return the result. The expression may contain parentheses that should be evaluated first.
For example, if the input is s = "T and (F or T)", the output should be True.
Algorithm Approach
The solution uses a stack-based approach to handle the expression evaluation:
- Split the string by spaces to get individual tokens
- Process each token based on its type (boolean value, operator, or parentheses)
- Use a stack to maintain operands and operators
- Handle parentheses by counting opening and closing brackets
- Evaluate sub-expressions when closing brackets are encountered
Implementation
class Solution:
def solve(self, s):
stack = []
op = {
"or": lambda x, y: x or y,
"and": lambda x, y: x and y,
}
for v in s.split():
if v[0] == "(":
stack.append(v[v.count("("):] == "T")
elif v.count(")") > 0:
ct = v.count(")")
stack.append(v[:-ct] == "T")
for _ in range(ct):
right = stack.pop()
o = stack.pop()
left = stack.pop()
stack.append(o(left, right))
elif v in ["T", "F"]:
stack.append(v == "T")
else:
stack.append(op[v])
if len(stack) > 1:
for i in range(0, len(stack) - 1, 2):
stack[i + 2] = stack[i + 1](stack[i], stack[i + 2])
return stack[-1]
return stack[0]
# Test the solution
ob = Solution()
s = "T and (F or T)"
print(ob.solve(s))
True
How It Works
Let's trace through the example "T and (F or T)":
-
"T": Push
Trueto stack -
"and": Push the
andoperator function to stack -
"(F": Push
Falseto stack (after removing opening bracket) -
"or": Push the
oroperator function to stack -
"T)": Push
Trueto stack, then evaluate the parentheses:- Pop
True,oroperator,False - Calculate:
False or True = True - Push result back to stack
- Pop
- Final evaluation:
True and True = True
Testing with Different Examples
ob = Solution()
# Test cases
test_cases = [
"T and F",
"T or F",
"F and (T or F)",
"(T and F) or (T and T)"
]
for test in test_cases:
result = ob.solve(test)
print(f"'{test}' ? {result}")
'T and F' ? False 'T or F' ? True 'F and (T or F)' ? False '(T and F) or (T and T)' ? True
Key Features
- Stack-based evaluation: Handles operator precedence naturally
- Parentheses handling: Counts brackets to manage nested expressions
- Lambda operators: Clean way to store and apply boolean operations
- Token processing: Splits by spaces for easy parsing
Conclusion
This stack-based approach effectively evaluates boolean expressions with parentheses by processing tokens sequentially and maintaining operator precedence. The algorithm handles complex nested expressions while keeping the code clean and readable.
