Evaluate Nested Comparison Rules Over a List of Records
Data Structure DesignAuto-graded · 19 test casesLast updated
Evaluate a nested rule tree of greater-than, less-than, AND and OR nodes against records, keeping matches in order and treating missing or mismatched fields as false.
You are given a list of records and a rule that describes which records to keep. Each record is a dictionary mapping field names to values. The rule is a tree built from dictionaries. Return the records that satisfy the rule, in their original order.
Rule format
Every node is a dictionary with a string key "op". There are two kinds of node.
Comparison nodes ("op" is "gt" or "lt") have two more keys:
"field": a string, the name of the field to inspect."value": the constant to compare against.
"gt" holds when the record's field value is strictly greater than value. "lt" holds when it is strictly less than value.
Logical nodes ("op" is "and" or "or") have one more key:
"children": a non-empty list of rule nodes.
An "and" node holds when all of its children hold. An "or" node holds when at least one child holds. Nodes can be nested to any depth.
Comparison semantics
A comparison node evaluates to False for a record when:
- the record does not contain
field, or - the field value and the constant are not of compatible types.
Two values are compatible if both are numbers (int or float, but not bool) or both are strings. Numbers are compared numerically and strings in standard lexicographic order. Any other pairing, such as a number against a string, or any bool, makes the comparison False.
Validation
If the rule is malformed, raise ValueError. A node is malformed when:
- it is not a dictionary, or its
"op"is missing or is not a string, - its
"op"is not one of"gt","lt","and","or", - a comparison node has a
"field"that is not a string, or has no"value"key, - a logical node has
"children"that is not a list, or is an empty list.
Validity is judged for each node as it is evaluated against a record, so a malformed node that is never reached (for example because of short-circuiting) does not need to raise.
Task
Implement the function so that it returns a new list containing the records for which the rule holds, preserving input order.
Constraints
- Records are dictionaries with string keys.
- The rule tree can be nested to any reasonable depth.
"and"and"or"take one or more children.- Field values and constants are numbers or strings in normal usage, though other types may appear and must follow the compatibility rule above.
- The input list may be empty, in which case the result is an empty list.
Examples
Example 1
Input: select_matching_records([{'id': 1, 'score': 85, 'age': 30}, {'id': 2, 'score': 40, 'age': 25}, {'id': 3, 'score': 60, 'age': 70}, {'id': 4, 'score': 95, 'age': 45}], {'op': 'or', 'children': [{'op': 'and', 'children': [{'op': 'gt', 'field': 'score', 'value': 50}, {'op': 'lt', 'field': 'age', 'value': 40}]}, {'op': 'gt', 'field': 'age', 'value': 65}]})
Output: [{'id': 1, 'score': 85, 'age': 30}, {'id': 3, 'score': 60, 'age': 70}]
Hints
Hint 1
Write a recursive helper that takes one record and one rule node and returns True or False. The top-level function just keeps the records for which the helper returns True.
Hint 2
For a comparison node, check in order: the field exists, the types are compatible (both numbers excluding bool, or both strings), then apply the strict comparison. Any failed check gives False.
Hint 3
For logical nodes, `all` and `any` over a generator give short-circuit evaluation for free. Validate each node's shape (op is a string, children is a non-empty list, field is a string, value key is present) before using it, and raise ValueError for an unknown op.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the rule as a tree and evaluate it recursively for each record.
- A comparison node is a leaf. It looks up the field in the record. If the field is missing, or the record value and the constant are not both numbers (excluding
bool) or both strings, the leaf isFalse. Otherwise it applies a strict>or<. - An
"and"node isTrueonly if every child isTrue, and an"or"node isTrueif any child isTrue. Python'sallandanyover a generator stop at the first deciding child, which gives early exit. - Each node's shape is validated when it is reached: it must be a dict with a string
op, comparison nodes need a stringfieldand avaluekey, logical nodes need a non-empty list ofchildren, and unknown operators raiseValueError. - The top-level function keeps each record for which the rule holds, in a list comprehension, so input order is preserved and a new list is returned.
Why it is correct
The rule is a finite tree, and each node's truth value is defined purely in terms of the record and its children's truth values. The recursion therefore computes exactly that definition. Mapping every missing or mismatched case to False in one place keeps the policy consistent. Short-circuiting does not change the result because and and or are determined as soon as one child decides them.
New operators would only need one more branch in the helper (or a lookup table from operator name to function), without changing the filtering loop.
Complexity
With n records and a rule of m nodes, the time is O(n · m) in the worst case, and less when short-circuiting applies. The extra space is O(d) for the recursion depth d of the rule, plus the output list.
Reference solution
from typing import List, Dict
def select_matching_records(records: List[Dict[str, object]], rule: Dict[str, object]) -> List[Dict[str, object]]:
def is_number(x):
return isinstance(x, (int, float)) and not isinstance(x, bool)
def holds(record, node):
if not isinstance(node, dict) or not isinstance(node.get("op"), str):
raise ValueError("invalid rule node")
op = node["op"]
if op in ("gt", "lt"):
field = node.get("field")
if not isinstance(field, str) or "value" not in node:
raise ValueError("invalid comparison node")
if field not in record:
return False
actual = record[field]
expected = node["value"]
compatible = (is_number(actual) and is_number(expected)) or (
isinstance(actual, str) and isinstance(expected, str)
)
if not compatible:
return False
if op == "gt":
return actual > expected
return actual < expected
if op in ("and", "or"):
children = node.get("children")
if not isinstance(children, list) or not children:
raise ValueError("logical nodes need non-empty children")
if op == "and":
return all(holds(record, child) for child in children)
return any(holds(record, child) for child in children)
raise ValueError("unknown operator")
return [record for record in records if holds(record, rule)]