Rule Engine with Operator Precedence and Quoted Strings
StringsModel answerLast updated
Build a transaction filter that evaluates accept/block rules in sequence, supporting field equality, boolean logic, AND/OR operators, and parentheses.
You're building a rule-based transaction filter. Given a transaction represented as a dictionary and an ordered list of rules, determine whether to accept or block the transaction.
Core behavior:
- Rules are checked top-to-bottom; the first matching rule determines the outcome
- Each rule is a tuple
(condition, outcome)where outcome is"accept"or"block" - If no rules match, default to
"accept" - All inputs are well-formed
Example:
transaction = {"merchant": "Corner Store", "country": "US"}
rules = [
('country == "FR"', "block"),
('merchant == "Corner Store"', "accept"),
]
evaluate(transaction, rules) # Returns "accept"
Implement this in three progressive stages:
Stage 1: Basic equality
Handle conditions comparing one field to one string literal using ==. String literals appear in double quotes. Either operand order should work (field == literal or literal == field).
Stage 2: Boolean logic Add support for:
- Boolean field checks (fields that hold true/false values)
ANDandORoperators combining conditions- Proper tokenization so strings containing "and" or "or" don't break parsing
- Standard precedence: AND binds tighter than OR
Stage 3: Parentheses Support arbitrary nesting of conditions with parentheses to override precedence.
Example: (country == "US" OR country == "CA") AND merchant == "Corner Store"
Clarifications needed:
- How should missing fields be handled in comparisons?
- Are operators case-sensitive?
- How are quotes escaped within string literals?
- How are boolean values represented in conditions?
Hints
Hint 1
Separate tokenization from parsing—handle quoted strings as single tokens first
Hint 2
Keep each stage's tests passing as you add features; first-match semantics must survive
Hint 3
For precedence, consider recursive descent parsing or converting to postfix notation
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires building a multi-stage parser and evaluator. The key insight is to separate concerns: tokenization handles quoted strings, parsing builds a structure respecting precedence, and evaluation walks that structure.
Stage 1: String Equality
Start with a simple split-and-compare approach:
def evaluate(transaction, rules):
for condition, outcome in rules:
if evaluate_condition(condition, transaction):
return outcome
return "accept"
def evaluate_condition(condition, transaction):
# Parse: field == "value" or "value" == field
parts = condition.split("==")
left = parts[0].strip()
right = parts[1].strip()
# Determine which is the field and which is the literal
if left.startswith('"') and left.endswith('"'):
literal = left[1:-1]
field = right
else:
literal = right[1:-1]
field = left
return transaction.get(field) == literal
Key decisions:
- Use
.get(field)to returnNonefor missing fields, which won't equal any string - Strip whitespace around operators
- Handle either operand order
Stage 2: AND/OR Logic
Now tokenization becomes critical. Split the condition into tokens while preserving quoted strings:
def tokenize(condition):
tokens = []
current = ""
in_quotes = False
i = 0
while i < len(condition):
char = condition[i]
if char == '"':
in_quotes = not in_quotes
current += char
elif char in (' ', '\t') and not in_quotes:
if current:
tokens.append(current)
current = ""
else:
current += char
i += 1
if current:
tokens.append(current)
return tokens
Then parse with precedence (AND before OR):
def parse_condition(tokens):
# Handle OR (lowest precedence)
for i, token in enumerate(tokens):
if token.upper() == "OR":
left = parse_condition(tokens[:i])
right = parse_condition(tokens[i+1:])
return ("OR", left, right)
# Handle AND (higher precedence)
for i, token in enumerate(tokens):
if token.upper() == "AND":
left = parse_condition(tokens[:i])
right = parse_condition(tokens[i+1:])
return ("AND", left, right)
# Base case: single comparison
return parse_comparison(tokens)
def parse_comparison(tokens):
# Find == operator
for i, token in enumerate(tokens):
if token == "==":
left = tokens[i-1]
right = tokens[i+1]
return ("==", left, right)
# Boolean field (no operator)
return ("bool", tokens[0])
Evaluation walks the parse tree:
def evaluate_parsed(node, transaction):
if node[0] == "OR":
return evaluate_parsed(node[1], transaction) or evaluate_parsed(node[2], transaction)
elif node[0] == "AND":
return evaluate_parsed(node[1], transaction) and evaluate_parsed(node[2], transaction)
elif node[0] == "==":
left_val = get_value(node[1], transaction)
right_val = get_value(node[2], transaction)
return left_val == right_val
elif node[0] == "bool":
field = node[1]
return transaction.get(field, False)
def get_value(token, transaction):
if token.startswith('"') and token.endswith('"'):
return token[1:-1]
return transaction.get(token)
Precedence handling: By checking for OR first in the token list, we give it lower precedence. When we find OR, we split there and recursively parse each side. The recursive call on the right side will find AND operators before returning, binding them tighter.
Test case for embedded keywords:
transaction = {"merchant": "Land and Sea Market"}
rules = [('merchant == "Land and Sea Market"', "accept")]
# Should match—the "and" is inside quotes
Stage 3: Parentheses
Extend tokenization to preserve parentheses as tokens, then handle them during parsing:
def parse_condition(tokens):
# Remove outer parentheses if present
if tokens[0] == "(" and find_matching_paren(tokens, 0) == len(tokens) - 1:
return parse_condition(tokens[1:-1])
# Find OR outside parentheses
depth = 0
for i, token in enumerate(tokens):
if token == "(":
depth += 1
elif token == ")":
depth -= 1
elif depth == 0 and token.upper() == "OR":
return ("OR", parse_condition(tokens[:i]), parse_condition(tokens[i+1:]))
# Find AND outside parentheses
depth = 0
for i, token in enumerate(tokens):
if token == "(":
depth += 1
elif token == ")":
depth -= 1
elif depth == 0 and token.upper() == "AND":
return ("AND", parse_condition(tokens[:i]), parse_condition(tokens[i+1:]))
return parse_comparison(tokens)
def find_matching_paren(tokens, start):
depth = 1
for i in range(start + 1, len(tokens)):
if tokens[i] == "(":
depth += 1
elif tokens[i] == ")":
depth -= 1
if depth == 0:
return i
return -1
Critical insight: Only split on operators that are outside all parentheses (depth == 0). This ensures (A OR B) AND C parses as AND at the top level, not OR.
Complexity
- Tokenization: O(n) where n is condition length
- Parsing: O(t²) worst case where t is token count (scanning for operators at each level)
- Evaluation: O(t) to walk the tree
- Overall per rule: O(n²) worst case, O(n) typical
Common Mistakes
- Breaking quoted strings: Splitting on whitespace or operators without checking quote context
- Wrong precedence: Parsing left-to-right instead of respecting AND before OR
- Short-circuit failure: Re-evaluating subexpressions instead of using Python's built-in boolean short-circuiting
- Type confusion: Comparing boolean fields as strings
"true"vs actual PythonTrue - Not preserving earlier behavior: Adding Stage 3 features that break Stage 1 tests
Using the AI Assistant
When working with an AI assistant on this problem:
- Specify tokenization rules explicitly: "Quoted strings must stay intact as single tokens"
- Request tests: "Write a test where a merchant name contains the word 'and'"
- Review carefully: AI-generated parsers often get precedence wrong or fail on edge cases
- Iterate with failed tests: Show the assistant actual failures rather than describing them abstractly