Mini Policy Engine: Boolean Rule Evaluation for Post Routing
StringsAuto-graded · 22 test casesLast updated
Tests whether a candidate can build a recursive-descent parser for a small boolean expression language and wire it into a first-match rule dispatcher.
Mini Policy Engine: Boolean Rule Evaluation for Post Routing
You are building the routing layer for a community platform. Every submitted post must be placed into exactly one of three queues — SHOW, HOLD, or TAKEDOWN — by evaluating a list of human-readable rules against the post's fields.
Posts and rules
A post is a plain dictionary mapping field names (strings) to values that are either numbers or strings, for example:
{"author_strikes": 2, "region": "EU", "word_count": 40, "hours_since_signup": 3}
This is only illustrative; do not assume a fixed schema.
A rule is a pair (condition_string, action) where action is one of "SHOW", "HOLD", or "TAKEDOWN".
Given an ordered list of rules and a batch of posts, return one action per post in the same order.
Dispatching
Evaluate the rules for each post from first to last and return the action of the first rule whose condition is true. If no rule matches, return "SHOW" for that post.
Condition language
Condition strings are built from three layers, each adding to the last.
Layer 1 — single comparison
field OP literal
fieldis an identifier ([A-Za-z_][A-Za-z0-9_]*).OPis one of==,!=,>,>=,<,<=.literalis either a number (integer or decimal, optionally negative) or a double-quoted string such as"EU".
A comparison is strictly false — never an error — when:
- the field is absent from the post, or
- the types of the post value and the literal are incompatible (e.g., applying
>between a string field and a numeric literal).
Layer 2 — chained AND / OR, no operator precedence
Multiple comparisons may be joined with AND or OR. There is no precedence between them: the expression is evaluated strictly left to right. For example:
region == "EU" OR region == "UK" AND hours_since_signup < 1
groups as:
(region == "EU" OR region == "UK") AND hours_since_signup < 1
Layer 3 — parentheses
Parentheses override left-to-right grouping and may be nested to any depth:
(region == "EU" OR region == "UK") AND author_strikes == 0
An unbalanced parenthesis must raise a ValueError.
Constraints
1 <= len(rules) <= 501 <= len(posts) <= 500- Each condition string is between 1 and 500 characters long.
- Every
actionin the input is one of"SHOW","HOLD","TAKEDOWN"; raiseValueErrorfor anything else. - Field names in conditions may refer to fields the post does not have; this makes only that comparison false.
- Numeric literals are integers or decimals (e.g.,
3,-1,2.5); scientific notation is not required. - String literals are enclosed in double quotes and contain no escaped characters beyond
\"and\\. ANDandORare case-insensitive keywords; field names that spell outandororare not valid input.
Examples
Example 1
Input: moderate_posts([['author_strikes > 3', 'TAKEDOWN'], ['(region == "EU" OR region == "UK") AND hours_since_signup < 1', 'HOLD']], [{'id': 'q7', 'author_strikes': 1, 'region': 'UK', 'hours_since_signup': 0}])
Output: ['HOLD']
Example 2
Input: moderate_posts([['word_count > 50', 'HOLD']], [{'word_count': 75}, {'word_count': 50}])
Output: ['HOLD', 'SHOW']
Hints
Hint 1
Break the work into four independent pieces: tokenizing the text into a flat token list, parsing a single comparison from three consecutive tokens, recursively parsing a full boolean expression (with parentheses delegating back to the top-level parse function), and evaluating a parsed tree against one post. Keeping these separate means later changes only ever touch one piece.
Hint 2
For left-to-right AND/OR with no precedence, use a running-accumulator pattern rather than a precedence-climbing parser. Parse the first term into a node, then loop: if the next token is AND or OR, consume it, parse the next term, and immediately combine the new term with *everything accumulated so far* into a new node. By the time AND is seen in `A OR B AND C`, the node for `A OR B` is already th…
Hint 3
To handle parentheses without any extra parsing logic, extend the 'parse one term' step so that when it sees a `(`, it calls the top-level expression parser recursively and then expects a matching `)`. Nesting falls out automatically from the recursion — no depth tracking needed.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution is structured as four independent layers, each with a single responsibility. This keeps changes local: adding a new token type only touches the tokenizer, a new operator only touches the evaluator.
1. Tokenizer
A single regex pass converts the raw condition string into a flat list of typed tokens: LPAREN, RPAREN, CMP (comparison operator), LITERAL (string or number), FIELD (identifier), AND, OR. String literals are decoded with json.loads to handle escape sequences correctly. Numeric literals become int or float at this stage so the evaluator never does type conversion. Any character the regex cannot classify raises ValueError immediately.
2. Parser — single comparison (atom)
parse_atom consumes exactly three tokens — FIELD, CMP, LITERAL — and returns a ("compare", field, op, value) tuple. This is also where parentheses are handled: when the next token is LPAREN, the function consumes it, delegates to parse_expression (the full expression parser), then expects and consumes a matching RPAREN. Because it calls back into parse_expression, nesting works to any depth with no extra code.
3. Parser — left-to-right boolean chains (expression)
parse_expression implements the running-accumulator pattern. It parses one atom into node, then loops: while the next token is AND or OR, it consumes the keyword, parses the next atom, and immediately folds both into a new two-child tree node where node (everything so far) is the left child. By the time AND is seen in A OR B AND C, A OR B has already been folded into a single node that becomes the left side of the AND, giving strict left-to-right evaluation with no precedence distinction between the two operators.
4. Evaluator
_matches walks the tree recursively. For a compare node it looks up the field in the post (returning False if absent), applies a type guard (returning False on mismatch rather than raising), and then applies the operator. For and/or nodes it recurses and combines with Python's short-circuit and/or.
5. Dispatcher
Rules are compiled once up front so syntax errors are caught before any post is processed. Per post, rules are checked in order and the action of the first matching rule is returned. The default when nothing matches is "SHOW".
Why it is correct
- Left-to-right, no-precedence AND/OR: the accumulator pattern guarantees the left subtree always contains the entire prefix parsed so far, matching the specified semantics.
- Parentheses:
parse_atomcallingparse_expressionrecursively is exactly the standard recursive-descent trick for grouping; it requires no extra depth tracking. - Type safety: the guard in
_matchesensures string literals never compare against numeric fields (and vice versa), returningFalserather than raisingTypeError. - Missing fields: checked explicitly before the comparison, returning
False. - Unbalanced parens: after
parse_expressionreturns inside a(…)group, the code asserts the next token is)and raisesValueErrorif not.
Complexity
- Tokenizing one rule of length L: O(L).
- Parsing one rule with n tokens: O(n).
- Evaluating one post against one rule tree of size t: O(t).
- Overall: O(P × R × T) where P = number of posts, R = number of rules, T = average tree size. The first-match short-circuit means most posts exit early in practice.
- Space: O(T) per rule for the parse tree; O(R × T) total for all compiled rules.