Parsing A Boolean Expression in Python

Boolean expression parsing involves evaluating complex logical expressions containing AND, OR, and NOT operations. Python can parse these expressions recursively by breaking them down into smaller components.

Boolean Expression Format

A boolean expression can be one of the following ?

  • "t" − evaluates to True

  • "f" − evaluates to False

  • "!(expression)" − logical NOT of the inner expression

  • "&(expr1,expr2,...)" − logical AND of 2 or more expressions

  • "|(expr1,expr2,...)" − logical OR of 2 or more expressions

Algorithm Approach

We'll use a recursive approach with the following steps ?

  • Parse single characters 't' and 'f' directly

  • For operators, extract the operation type and recursively parse sub-expressions

  • Apply the logical operation to all parsed results

Implementation

class Solution:
    def parseBoolExpr(self, expression):
        result, position = self.solve(expression, 0)
        return result
    
    def solve(self, expr, i):
        # Base cases: single boolean values
        if expr[i] == "f":
            return False, i + 1
        elif expr[i] == "t":
            return True, i + 1
        
        # Extract operator and skip opening parenthesis
        operator = expr[i]
        i = i + 2
        
        # Collect results from sub-expressions
        results = []
        while expr[i] != ")":
            if expr[i] == ",":
                i += 1
                continue
            result, i = self.solve(expr, i)
            results.append(result)
        
        # Apply the operator
        if operator == "&":
            return all(results), i + 1
        elif operator == "|":
            return any(results), i + 1
        else:  # operator == "!"
            return not results[0], i + 1

# Test the solution
solution = Solution()
print(solution.parseBoolExpr("|(!(t),&(t,f,t))"))
print(solution.parseBoolExpr("&(t,t,t)"))
print(solution.parseBoolExpr("!(f)"))
False
True
True

How It Works

Let's trace through the example "|(!(t),&(t,f,t))" ?

  • Parse "|" operator with two sub-expressions

  • First sub-expression: "!(t)" − NOT of True = False

  • Second sub-expression: "&(t,f,t)" − AND of [True, False, True] = False

  • Final result: OR of [False, False] = False

Key Points

  • Recursive parsing: Each sub-expression is parsed independently

  • Position tracking: The function returns both result and next position

  • Built-in functions: Uses all() for AND and any() for OR operations

Conclusion

This recursive approach efficiently parses boolean expressions by breaking them into smaller components. The algorithm handles nested expressions naturally and uses Python's built-in all() and any() functions for clean logical operations.

Updated on: 2026-03-25T08:42:53+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements