- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to evaluate Boolean expression from a string in Python?
Suppose we have a string s containing a boolean expression with operators "and" and "or", evaluate it and return the result. Here the expressions may have parentheses, which should be evaluated first.
So, if the input is like s = "T and (F or T)", then the output will be True
To solve this, we will follow these steps:
stack := a new list
t = list of elements of s split by blank spaces
for each v in t, do
if v[0] is same as "(", then
push true when v[from index of "(" to end] is same as "T", into stack
otherwise when ")" is found, then
ct := number of closing bracket ")" in v
push true when v[from index 0 to size of v - ct] is same as "T" into stack
for each value in range 0 to ct-1, do
right := pop from stack
:= pop from stack
left := pop from stack
perform operation (left o right) and push into stack
otherwise when v is either "T" or "F", then
push true when v is same as "T" into stack
otherwise,
push op[v] into stack
if element count in stack > 1, then
for i in range 0 to size of stack - 1, increase by 2, do
stack[i + 2] := stack[i + 1](stack[i], stack[i + 2])
return top element of stack
return bottom element of stack
Let us see the following implementation to get better understanding:
Example
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] ob = Solution() s = "T and (F or T)" print(ob.solve(s))
Input
"T and (F or T)"
Output
True