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:


 Live Demo

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")

      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)"


"T and (F or T)"



Updated on: 10-Nov-2020


Kickstart Your Career

Get certified by completing the course

Get Started