Conditional Form Evaluator with Numeric and Boolean Rules

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement visible_questions(spec, raw_answers) for a dynamic form engine that validates a JSON-decoded form specification spec, parses raw string responses in raw_answers, evaluates visibility rules, and returns the ordered list of displayed question IDs.

Form Specification (spec)

spec["questions"] is an ordered list of question dictionaries. Each entry contains: - "id" (str): unique identifier across the form (duplicate IDs raise ValueError). - "prompt" (str): label shown to the user. - "type" (str): either "text" or "number" (any other type raises ValueError). - "condition" (optional): omitted or None if the question is always shown; otherwise either a leaf comparison or a boolean group: - Leaf comparison: a dictionary with exact string keys {"question_id", "operator", "value"} (missing keys, extra keys, or non-string field values raise ValueError). - "question_id" must refer to a question that appeared strictly earlier in spec["questions"] (unknown IDs, forward references, and self-references raise ValueError). - "operator" must match the referenced question's "type": - "text" questions allow "equals" and "not_equals". - "number" questions allow "equals", "not_equals", "greater_than", "greater_than_or_equal", "less_than", and "less_than_or_equal". - When "question_id" targets a "number" question, "value" must also be a valid numeric string at load time. - Boolean group: a dictionary with a single key — "all" (logical AND: true when every child is true) or "any" (logical OR: true when at least one child is true) — mapped to a non-empty list of child conditions, each of which may be a leaf comparison or another "all" / "any" group nested to arbitrary depth. Empty lists, non-list values, mixed keys ({"all": ..., "any": ...}), or non-dictionary nodes raise ValueError whose message includes the nested path (such as any[0].all[1]).

Answer Parsing & Visibility Semantics (raw_answers)

  • raw_answers maps answered question IDs to raw string inputs:
    • For "text" questions, strip leading and trailing whitespace (raw.strip()) and compare strings with exact case sensitivity.
    • For "number" questions, strip surrounding whitespace and accept an optional + or - sign, one or more ASCII digits 0-9, and an optional decimal point . followed by one or more ASCII digits 0-9 (for example "42", "-5", "+3", "007", "0.50", "-0"). Reject commas/underscores ("1,000", "1_000"), scientific notation ("1e3"), bare leading/trailing dots (".5", "5."), "nan", "inf", words, or blank strings with ValueError. Compare valid numbers by exact base-10 value (Decimal), not string order or binary floating point.
  • Validate the entire spec before evaluating answers.
  • If a referenced question is omitted from raw_answers (unanswered), any leaf comparison inspecting it returns False (even "not_equals").
  • If raw_answers supplies a response for a question whose own condition evaluates to False, that response is still parsed, validated, and available to later conditions.

Examples

Example 1

Input:
  spec = {
    "questions": [
      {"id": "transport_mode", "type": "text", "prompt": "Select transport mode"},
      {
        "id": "air_carrier",
        "type": "text",
        "prompt": "Which airline?",
        "condition": {"question_id": "transport_mode", "operator": "equals", "value": "air"}
      },
      {
        "id": "port_code",
        "type": "text",
        "prompt": "Origin port code",
        "condition": {"question_id": "transport_mode", "operator": "not_equals", "value": "air"}
      }
    ]
  }
  raw_answers = {"transport_mode": "  air  "}
Output: ["transport_mode", "air_carrier"]

" air " trims to "air", so air_carrier's "equals" check succeeds while port_code's "not_equals" check is False.

Example 2

Input:
  spec = {
    "questions": [
      {"id": "weight_kg", "type": "number", "prompt": "Package weight (kg)"},
      {
        "id": "heavy_lift_fee",
        "type": "number",
        "prompt": "Heavy-lift surcharge",
        "condition": {"question_id": "weight_kg", "operator": "greater_than", "value": "250"}
      }
    ]
  }
  raw_answers = {"weight_kg": "250.05"}
Output: ["weight_kg", "heavy_lift_fee"]

Both "250.05" and "250" are parsed as exact base-10 numbers; since 250.05 > 250, heavy_lift_fee is included.

Example 3

Input:
  spec = {
    "questions": [
      {"id": "cargo_class", "type": "text", "prompt": "Cargo classification"},
      {"id": "declared_value", "type": "number", "prompt": "Declared value (USD)"},
      {
        "id": "customs_broker",
        "type": "text",
        "prompt": "Assigned customs broker",
        "condition": {
          "any": [
            {
              "all": [
                {"question_id": "cargo_class", "operator": "equals", "value": "hazmat"},
                {"question_id": "declared_value", "operator": "greater_than", "value": "2500"}
              ]
            },
            {"question_id": "declared_value", "operator": "greater_than_or_equal", "value": "15000"}
          ]
        }
      }
    ]
  }
  raw_answers = {"cargo_class": "standard", "declared_value": "15000.00"}
Output: ["cargo_class", "declared_value", "customs_broker"]

customs_broker requires (cargo_class == "hazmat" AND declared_value > 2500) OR declared_value >= 15000. Although cargo_class is "standard" (making the "all" group False), 15000.00 >= 15000 satisfies the second branch of "any", so customs_broker is visible.

Constraints

  • 0 <= len(spec["questions"]) <= 5,000
  • Condition trees can nest "all" and "any" groups to arbitrary depth within standard Python recursion bounds.
  • Numeric strings may contain high-precision fractional digits that exceed 64-bit IEEE-754 float precision (use exact base-10 arithmetic).
  • Every malformed definition or invalid numeric answer must raise ValueError.

Step-by-step walkthrough

  1. Understand the three-stage form pipeline

    Our evaluator visible_questions(spec, raw_answers) runs a clean three-stage pipeline from raw dictionaries to displayed question IDs:

      spec (JSON dict)  ──►  parse_questionnaire()  ──►  List[Question]
                                                               │
      raw_answers       ──►  parse_answer()         ──►  answers (typed)
                                                               │
                                                               ▼
                                                         evaluate()  ──►  visible IDs
    

    Every rule fits cleanly into one of those stages while keeping plain "text" forms 100% compatible:

    • Valid numbers: optional + or -, one or more ASCII digits 0-9, and an optional .digits fractional suffix (with outer whitespace trimmed). Inputs like 42, -5, +3, 007, and 0.50 succeed; 1,000, 1e3, 1_000, .5, 5., inf, nan, and "" raise ValueError immediately.
    • Allowed operators: "text" allows equals and not_equals. "number" adds greater_than, greater_than_or_equal, less_than, and less_than_or_equal.
    • Earlier-only references: a condition may only inspect a question defined strictly earlier in spec["questions"] (validated at load time, ruling out self-references and cycles).
    • Nested boolean groups: {"all": [...]} represents AND and {"any": [...]} represents OR. Each group has a single key and a non-empty list, while leaf conditions keep their three-key shape.
    • Unanswered and hidden questions: any leaf inspecting an unanswered question returns False (even not_equals), and answers to hidden questions remain available to later conditions.
  2. Parse numbers at the boundary with exact Decimals

    If numeric responses stayed as strings, "90" > "250" would evaluate to True because strings use lexicographical comparison — comparing character by character from left to right ('9' > '2'). Equality would also break ("15000.00" != "15000").

    So raw strings must convert into numbers at the boundary: when loading condition thresholds and when parsing user responses. Why combine a strict regex with Decimal instead of calling float()?

    • float() silently accepts "inf", "nan", "1e3", and "1_000".
    • Binary float rounds "250.00000000000000001" down to 250.0, losing strict inequality against 250, whereas Decimal(text) preserves exact base-10 digits and satisfies Decimal("15000.00") == Decimal("15000").
    OPERATORS = {
        "text": {"equals", "not_equals"},
        "number": {
            "equals",
            "not_equals",
            "greater_than",
            "greater_than_or_equal",
            "less_than",
            "less_than_or_equal",
        },
    }
    
    LEAF_KEYS = {"question_id", "operator", "value"}
    
    # Optional sign, ASCII digits [0-9], optional decimal part.
    NUMBER_PATTERN = re.compile(r"[+-]?[0-9]+(\.[0-9]+)?")
    
    
    def parse_number(raw: str) -> Decimal:
        """Validate a numeric string and convert it into an exact Decimal."""
        if not isinstance(raw, str):
            raise ValueError(f"not a string: {raw!r}")
        text = raw.strip()
        if not NUMBER_PATTERN.fullmatch(text):
            raise ValueError(f"not a number: {raw!r}")
        return Decimal(text)
    
  3. Validate leaf comparisons at load time

    Broken rules inside spec — such as greater_than on a "text" field, "value": "two-fifty" on a "number" field, or pointing at a later or missing field — are schema mistakes. Rejecting them inside parse_leaf fails fast as soon as spec loads, even when raw_answers is empty.

    @dataclass
    class Condition:
        # Leaf node in a condition tree, e.g. Condition("weight_kg", "greater_than", Decimal("250")).
        question_id: str  # ID of an earlier question whose answer is inspected
        operator: str     # operator name validated against the target question's type
        value: Any        # str for "text" questions, Decimal for "number" questions
    
    
    def parse_leaf(raw_cond: dict, earlier: Dict[str, Question], where: str) -> Condition:
        """Validate and build a single comparison node against an earlier question."""
        # Phase 1: Check that all required string fields exist and no stray keys were added.
        for key in ("question_id", "operator", "value"):
            if key not in raw_cond:
                raise ValueError(f"{where}: missing {key!r}")
            if not isinstance(raw_cond[key], str):
                raise ValueError(f"{where}: {key!r} must be a string")
        extra_keys = set(raw_cond.keys()) - LEAF_KEYS
        if extra_keys:
            raise ValueError(f"{where}: unexpected keys {sorted(extra_keys)!r}")
    
        # Phase 2: Ensure the referenced question appeared earlier in the questionnaire.
        target = earlier.get(raw_cond["question_id"])
        if target is None:
            raise ValueError(f"{where}: {raw_cond['question_id']!r} is not an earlier question")
    
        # Phase 3: Validate operator compatibility and pre-parse numeric threshold values.
        operator = raw_cond["operator"]
        if operator not in OPERATORS[target.type]:
            raise ValueError(
                f"{where}: operator {operator!r} is not allowed on "
                f"{target.type} question {target.id!r}"
            )
    
        parsed_value: Any = raw_cond["value"]
        if target.type == "number":
            try:
                parsed_value = parse_number(raw_cond["value"])
            except ValueError:
                raise ValueError(f"{where}: {raw_cond['value']!r} is not a number") from None
    
        return Condition(target.id, operator, parsed_value)
    
  4. Represent nested AND/OR logic as an expression tree

    Look at Example 3's rule for customs_broker: (cargo_class == "hazmat" AND declared_value > 2500) OR declared_value >= 15000. Using {"any": [...]} for OR and {"all": [...]} for AND models any nested rule as an expression tree — a tree where interior Group nodes combine child booleans and Condition leaves evaluate single comparisons:

                           Group(mode="any")             <-- OR
                          /                 \
            Group(mode="all")         Condition(declared_value >= 15000)
              /           \
    Condition(           Condition(
      cargo_class          declared_value > 2500
      == "hazmat"        )
    )
    

    Why this representation stays clean: - No precedence ambiguity: each dictionary's nesting directly specifies which group sits inside which. - Backward compatible: any leaf {"question_id": ..., "operator": ..., "value": ...} lacks "all" and "any", so single comparisons need no extra wrapper.

    @dataclass
    class Group:
        # Interior node in a condition tree, e.g. Group("any", [Group("all", [...]), Condition(...)]).
        mode: str         # "all" (logical AND) or "any" (logical OR)
        parts: list       # non-empty list of child Condition or Group nodes
    
    
    @dataclass
    class Question:
        id: str
        prompt: str
        type: str                                           # "text" or "number"
        condition: Optional[Union[Condition, Group]] = None
    
  5. Parse condition groups recursively with error paths

    parse_condition inspects raw_cond for "all" or "any": - When neither key is present, it delegates to parse_leaf. - Otherwise, it checks len(raw_cond) == 1 (rejecting ambiguous {"all": [...], "any": [...]}) and requires a non-empty list (since Python's all([]) is vacuously True, which would mask a broken rule). - Passing f"{where}.{mode}[{idx}]" into each recursive call produces an exact breadcrumb such as question 'customs_broker': condition.any[0].all[1] whenever a deeply nested leaf fails validation.

    In parse_questionnaire, each Question is inserted into earlier after parsing its own condition, so self-references fail automatically.

    def parse_condition(raw_cond: Any, earlier: Dict[str, Question], where: str) -> Union[Condition, Group]:
        """Recursively parse either an AND/OR group ({'all': [...]}/{'any': [...]}) or a leaf."""
        if not isinstance(raw_cond, dict):
            raise ValueError(f"{where}: a condition must be an object")
    
        # Without "all" or "any", treat the dictionary as a single leaf comparison.
        if "all" not in raw_cond and "any" not in raw_cond:
            return parse_leaf(raw_cond, earlier, where)
    
        # Disallow mixing keys like {"all": [...], "any": [...]} so precedence is never ambiguous.
        if len(raw_cond) != 1:
            raise ValueError(f"{where}: a group must have exactly one key, 'all' or 'any'")
    
        mode = "all" if "all" in raw_cond else "any"
        items = raw_cond[mode]
        # Reject empty groups: all([]) is vacuously True and any([]) is False, hiding author bugs.
        if not isinstance(items, list) or not items:
            raise ValueError(f"{where}.{mode}: must be a non-empty list")
    
        parts = []
        for idx, item in enumerate(items):
            child_where = f"{where}.{mode}[{idx}]"
            parts.append(parse_condition(item, earlier, child_where))
        return Group(mode, parts)
    
    
    def parse_questionnaire(spec: dict) -> List[Question]:
        """Parse and validate all questions in order, catching broken definitions at load time."""
        questions = []
        # earlier: maps question_id -> Question for questions strictly before the current one.
        earlier: Dict[str, Question] = {}
    
        for raw_q in spec["questions"]:
            q_id = raw_q["id"]
            q_type = raw_q["type"]
            if q_type not in OPERATORS:
                raise ValueError(f"question {q_id!r}: unsupported type {q_type!r}")
            if q_id in earlier:
                raise ValueError(f"question {q_id!r}: duplicate id")
    
            condition = None
            if raw_q.get("condition") is not None:
                where = f"question {q_id!r}: condition"
                condition = parse_condition(raw_q["condition"], earlier, where)
    
            question = Question(q_id, raw_q["prompt"], q_type, condition)
            questions.append(question)
            # Register in `earlier` AFTER parsing its own condition so self-references fail too.
            earlier[question.id] = question
    
        return questions
    
  6. Evaluate leaves, groups, and visible questions

    Because load-time validation already verified operators and converted numeric thresholds to Decimal, evaluate_leaf compares answer against condition.value directly.

    evaluate uses evaluate_leaf at the leaves and combines Group nodes via short-circuit evaluation — returning False from "all" as soon as one child fails, and returning True from "any" as soon as one child succeeds:

    def parse_answer(question: Question, raw: str) -> Any:
        """Convert a user's raw string answer into the typed value expected by `question`."""
        if question.type == "text":
            return raw.strip()
        if question.type == "number":
            try:
                return parse_number(raw)
            except ValueError:
                raise ValueError(f"question {question.id!r}: {raw!r} is not a number") from None
        raise ValueError(f"unsupported question type: {question.type}")
    
    
    def evaluate_leaf(condition: Condition, answers: Dict[str, Any]) -> bool:
        """Evaluate one comparison against parsed answers; unanswered questions never match."""
        answer = answers.get(condition.question_id)
        if answer is None:
            return False
    
        op = condition.operator
        if op == "equals":
            return answer == condition.value
        if op == "not_equals":
            return answer != condition.value
    
        # Ordering operators were validated at load time to belong only to "number" questions,
        # so both `answer` and `condition.value` are exact Decimal instances here.
        if op == "greater_than":
            return answer > condition.value
        if op == "greater_than_or_equal":
            return answer >= condition.value
        if op == "less_than":
            return answer < condition.value
        if op == "less_than_or_equal":
            return answer <= condition.value
        raise ValueError(f"unsupported operator: {op}")
    
    
    def evaluate(condition: Union[Condition, Group], answers: Dict[str, Any]) -> bool:
        """Evaluate a leaf Condition or recursively short-circuit an AND/OR Group."""
        if isinstance(condition, Condition):
            return evaluate_leaf(condition, answers)
    
        if condition.mode == "all":
            for part in condition.parts:
                if not evaluate(part, answers):
                    return False
            return True
    
        # condition.mode == "any"
        for part in condition.parts:
            if evaluate(part, answers):
                return True
        return False
    
    
    def visible_ids(questions: List[Question], answers: Dict[str, Any]) -> List[str]:
        """Return IDs of questions with no condition or whose condition evaluates to True."""
        result = []
        for question in questions:
            if question.condition is None or evaluate(question.condition, answers):
                result.append(question.id)
        return result
    
    
    def visible_questions(spec: Dict, raw_answers: Dict[str, str]) -> List[str]:
        # Phase 1: Parse and validate the questionnaire definition.
        questions = parse_questionnaire(spec)
    
        # Phase 2: Parse answers for every answered question in the questionnaire.
        # Answers to hidden questions are still parsed and stored, preserving existing behavior.
        answers: Dict[str, Any] = {}
        for question in questions:
            if question.id in raw_answers:
                answers[question.id] = parse_answer(question, raw_answers[question.id])
    
        # Phase 3: Evaluate visibility in questionnaire order.
        return visible_ids(questions, answers)
    
  7. Trace Example 3 across answer combinations

    Let's trace customs_broker's rule (cargo_class == "hazmat" AND declared_value > 2500) OR declared_value >= 15000 on five cases:

    Case 1 (Example 3): cargo_class="standard", declared_value="15000.00"
      - all[0]: "standard" == "hazmat" -> False (Group("all") short-circuits to False)
      - any[1]: Decimal("15000.00") >= Decimal("15000") -> True
      - Group("any") -> True  (customs_broker shown: >= is inclusive and 15000.00 == 15000)
    
    Case 2: cargo_class="hazmat", declared_value="3000"
      - all[0]: "hazmat" == "hazmat"              -> True
      - all[1]: Decimal("3000") > Decimal("2500") -> True
      - Group("all") -> True; Group("any") short-circuits -> True  (customs_broker shown)
    
    Case 3: cargo_class="hazmat", declared_value="2500"
      - all[0] -> True; all[1]: 2500 > 2500 -> False -> Group("all") = False
      - any[1]: 2500 >= 15000 -> False -> Group("any") = False  (customs_broker hidden: > is strict)
    
    Case 4: cargo_class="hazmat", declared_value="9"
      - Decimal("9") > Decimal("2500") is False (numeric, not string "9" > "2500")
      - Group("any") -> False  (customs_broker hidden)
    
    Case 5: cargo_class unanswered, declared_value="20000"
      - all[0]: answers.get("cargo_class") is None -> False -> Group("all") = False
      - any[1]: Decimal("20000") >= Decimal("15000") -> True -> Group("any") = True  (shown)
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import re
    from dataclasses import dataclass
    from decimal import Decimal
    from typing import Union
    
    # OPERATORS: maps each supported question type to the set of valid comparison operators.
    OPERATORS = {
        "text": {"equals", "not_equals"},
        "number": {
            "equals",
            "not_equals",
            "greater_than",
            "greater_than_or_equal",
            "less_than",
            "less_than_or_equal",
        },
    }
    
    # LEAF_KEYS: the exact set of keys required on a single comparison object.
    LEAF_KEYS = {"question_id", "operator", "value"}
    
    # NUMBER_PATTERN: optional sign, ASCII digits [0-9] (not \d, which matches Unicode digits),
    # and optional fractional part. Rejects "1,000", "1e3", ".5", "5.", "inf", and "nan".
    NUMBER_PATTERN = re.compile(r"[+-]?[0-9]+(\.[0-9]+)?")
    
    
    def parse_number(raw: str) -> Decimal:
        """Validate a numeric string and convert it into an exact Decimal."""
        if not isinstance(raw, str):
            raise ValueError(f"not a string: {raw!r}")
        text = raw.strip()
        if not NUMBER_PATTERN.fullmatch(text):
            raise ValueError(f"not a number: {raw!r}")
        # Decimal preserves exact base-10 precision (unlike float, which rounds long decimals).
        return Decimal(text)
    
    
    @dataclass
    class Condition:
        # Leaf node in a condition tree, e.g. Condition("weight_kg", "greater_than", Decimal("250")).
        question_id: str  # ID of an earlier question whose answer is inspected
        operator: str     # operator name validated against the target question's type
        value: Any        # str for "text" questions, Decimal for "number" questions
    
    
    @dataclass
    class Group:
        # Interior node in a condition tree, e.g. Group("any", [Group("all", [...]), Condition(...)]).
        mode: str         # "all" (logical AND) or "any" (logical OR)
        parts: list       # non-empty list of child Condition or Group nodes
    
    
    @dataclass
    class Question:
        id: str
        prompt: str
        type: str                                           # "text" or "number"
        condition: Optional[Union[Condition, Group]] = None
    
    
    def parse_leaf(raw_cond: dict, earlier: Dict[str, Question], where: str) -> Condition:
        """Validate and build a single comparison node against an earlier question."""
        # Phase 1: Check that all required string fields exist and no stray keys were added.
        for key in ("question_id", "operator", "value"):
            if key not in raw_cond:
                raise ValueError(f"{where}: missing {key!r}")
            if not isinstance(raw_cond[key], str):
                raise ValueError(f"{where}: {key!r} must be a string")
        extra_keys = set(raw_cond.keys()) - LEAF_KEYS
        if extra_keys:
            raise ValueError(f"{where}: unexpected keys {sorted(extra_keys)!r}")
    
        # Phase 2: Ensure the referenced question appeared earlier in the questionnaire.
        target = earlier.get(raw_cond["question_id"])
        if target is None:
            raise ValueError(f"{where}: {raw_cond['question_id']!r} is not an earlier question")
    
        # Phase 3: Validate operator compatibility and pre-parse numeric threshold values.
        operator = raw_cond["operator"]
        if operator not in OPERATORS[target.type]:
            raise ValueError(
                f"{where}: operator {operator!r} is not allowed on "
                f"{target.type} question {target.id!r}"
            )
    
        parsed_value: Any = raw_cond["value"]
        if target.type == "number":
            try:
                parsed_value = parse_number(raw_cond["value"])
            except ValueError:
                raise ValueError(f"{where}: {raw_cond['value']!r} is not a number") from None
    
        return Condition(target.id, operator, parsed_value)
    
    
    def parse_condition(raw_cond: Any, earlier: Dict[str, Question], where: str) -> Union[Condition, Group]:
        """Recursively parse either an AND/OR group ({'all': [...]}/{'any': [...]}) or a leaf."""
        if not isinstance(raw_cond, dict):
            raise ValueError(f"{where}: a condition must be an object")
    
        # Without "all" or "any", treat the dictionary as a single leaf comparison.
        if "all" not in raw_cond and "any" not in raw_cond:
            return parse_leaf(raw_cond, earlier, where)
    
        # Disallow mixing keys like {"all": [...], "any": [...]} so precedence is never ambiguous.
        if len(raw_cond) != 1:
            raise ValueError(f"{where}: a group must have exactly one key, 'all' or 'any'")
    
        mode = "all" if "all" in raw_cond else "any"
        items = raw_cond[mode]
        # Reject empty groups: all([]) is vacuously True and any([]) is False, hiding author bugs.
        if not isinstance(items, list) or not items:
            raise ValueError(f"{where}.{mode}: must be a non-empty list")
    
        parts = []
        for idx, item in enumerate(items):
            child_where = f"{where}.{mode}[{idx}]"
            parts.append(parse_condition(item, earlier, child_where))
        return Group(mode, parts)
    
    
    def parse_questionnaire(spec: dict) -> List[Question]:
        """Parse and validate all questions in order, catching broken definitions at load time."""
        questions = []
        # earlier: maps question_id -> Question for questions strictly before the current one.
        earlier: Dict[str, Question] = {}
    
        for raw_q in spec["questions"]:
            q_id = raw_q["id"]
            q_type = raw_q["type"]
            if q_type not in OPERATORS:
                raise ValueError(f"question {q_id!r}: unsupported type {q_type!r}")
            if q_id in earlier:
                raise ValueError(f"question {q_id!r}: duplicate id")
    
            condition = None
            if raw_q.get("condition") is not None:
                where = f"question {q_id!r}: condition"
                condition = parse_condition(raw_q["condition"], earlier, where)
    
            question = Question(q_id, raw_q["prompt"], q_type, condition)
            questions.append(question)
            # Register in `earlier` AFTER parsing its own condition so self-references fail too.
            earlier[question.id] = question
    
        return questions
    
    
    def parse_answer(question: Question, raw: str) -> Any:
        """Convert a user's raw string answer into the typed value expected by `question`."""
        if question.type == "text":
            return raw.strip()
        if question.type == "number":
            try:
                return parse_number(raw)
            except ValueError:
                raise ValueError(f"question {question.id!r}: {raw!r} is not a number") from None
        raise ValueError(f"unsupported question type: {question.type}")
    
    
    def evaluate_leaf(condition: Condition, answers: Dict[str, Any]) -> bool:
        """Evaluate one comparison against parsed answers; unanswered questions never match."""
        answer = answers.get(condition.question_id)
        if answer is None:
            return False
    
        op = condition.operator
        if op == "equals":
            return answer == condition.value
        if op == "not_equals":
            return answer != condition.value
    
        # Ordering operators were validated at load time to belong only to "number" questions,
        # so both `answer` and `condition.value` are exact Decimal instances here.
        if op == "greater_than":
            return answer > condition.value
        if op == "greater_than_or_equal":
            return answer >= condition.value
        if op == "less_than":
            return answer < condition.value
        if op == "less_than_or_equal":
            return answer <= condition.value
        raise ValueError(f"unsupported operator: {op}")
    
    
    def evaluate(condition: Union[Condition, Group], answers: Dict[str, Any]) -> bool:
        """Evaluate a leaf Condition or recursively short-circuit an AND/OR Group."""
        if isinstance(condition, Condition):
            return evaluate_leaf(condition, answers)
    
        if condition.mode == "all":
            for part in condition.parts:
                if not evaluate(part, answers):
                    return False
            return True
    
        # condition.mode == "any"
        for part in condition.parts:
            if evaluate(part, answers):
                return True
        return False
    
    
    def visible_ids(questions: List[Question], answers: Dict[str, Any]) -> List[str]:
        """Return IDs of questions with no condition or whose condition evaluates to True."""
        result = []
        for question in questions:
            if question.condition is None or evaluate(question.condition, answers):
                result.append(question.id)
        return result
    
    
    def visible_questions(spec: Dict, raw_answers: Dict[str, str]) -> List[str]:
        # Phase 1: Parse and validate the questionnaire definition.
        questions = parse_questionnaire(spec)
    
        # Phase 2: Parse answers for every answered question in the questionnaire.
        # Answers to hidden questions are still parsed and stored, preserving existing behavior.
        answers: Dict[str, Any] = {}
        for question in questions:
            if question.id in raw_answers:
                answers[question.id] = parse_answer(question, raw_answers[question.id])
    
        # Phase 3: Evaluate visibility in questionnaire order.
        return visible_ids(questions, answers)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the form engine as a two-phase filter: first, load-time parsing compiles the JSON form specification into a validated expression tree — a tree structure where leaf nodes are single field comparisons (Condition) and interior nodes (Group) combine child results with all (AND) or any (OR) — while converting numeric threshold strings into exact base-10 Decimal numbers. Second, answer evaluation parses each raw string response according to its field type, treats any leaf comparison against an unanswered field as False, and bubbles True/False results up the tree using short-circuit evaluation (stopping early as soon as an all group hits False or an any group hits True).

Three naive shortcuts introduce subtle bugs here. First, leaving numeric answers as strings triggers lexicographical comparison (character-by-character alphabetical order), where "90" > "250" is True because '9' follows '2' and "15000.00" == "15000" is False. Second, validating numbers with Python's float() accepts "nan", "inf", and "1e3" while rounding high-precision decimals like "250.00000000000000001" down to 250.0. Third, deferring operator checks or threshold parsing until evaluation time hides schema bugs (such as greater_than on a "text" field) until a live user happens to exercise that branch.

Let's trace Example 3 (customs_broker displayed when (cargo_class == "hazmat" AND declared_value > 2500) OR declared_value >= 15000) with raw_answers = {"cargo_class": "standard", "declared_value": "15000.00"}: 1. Load specification: cargo_class (text) and declared_value (number) load first; customs_broker's condition compiles into Group("any", [Group("all", [Condition("cargo_class", "equals", "hazmat"), Condition("declared_value", "greater_than", Decimal("2500"))]), Condition("declared_value", "greater_than_or_equal", Decimal("15000"))]). 2. Parse responses: answers becomes {"cargo_class": "standard", "declared_value": Decimal("15000.00")}. 3. Evaluate tree: Inside Group("all"), "standard" == "hazmat" is False, so Group("all") short-circuits to False; the outer Group("any") then checks Decimal("15000.00") >= Decimal("15000"), which is True, returning ["cargo_class", "declared_value", "customs_broker"].

Complexity

Let Q be the number of questions, C the total number of condition nodes (Condition leaves plus Group branches) across the form, and L the total character length of raw answers and condition threshold strings.

  • Time — O(Q + C + L): parse_questionnaire visits each of the Q questions and C condition nodes once, performing O(1) dictionary lookups in earlier and linear-time regex/Decimal conversions over string characters (O(L) total, assuming bounded-length numbers). visible_questions then parses at most Q answers and visits each of the C condition nodes at most once.
  • Space — O(Q + C + L): storing the Q Question objects, the C tree nodes, and the parsed Decimal/string values takes O(Q + C + L) memory, plus O(D) call-stack frames during recursive parsing and evaluation for maximum group nesting depth D (D <= C).

Edge cases

  • Text trimming and case sensitivity: Surrounding whitespace is stripped (" air " matches "air"), casing remains exact ("Air" does not match), and answers to hidden fields still count if referenced later.
  • Number formatting: "-5", "+3", " 42 ", "007", "0.50", and "-0" (equal to 0) are valid; "1,000", "1e3", "1_000", ".5", "5.", "inf", "nan", and blank strings raise ValueError.
  • Exact decimal boundaries: Decimal("250") is False for greater_than 250 and True for greater_than_or_equal 250; "250.00000000000000001" remains strictly greater than "250".
  • Unanswered fields inside groups: A missing answer evaluates its own leaf to False (even for not_equals), making an enclosing all group False while still letting another branch of an any group succeed.
  • Forward, self, and duplicate references: Registering a question in earlier only after parsing its condition rejects both forward references and self-references at load time.
  • Malformed groups and leaves: Empty lists ({"all": []}), mixed keys ({"all": [...], "any": [...]}), non-string leaf fields, and extra keys all fail at load time with a path-prefixed ValueError.

Common mistakes

  • Comparing numeric strings without converting to numbers: Causes "90" > "250" to evaluate to True and "15000.00" == "15000" to evaluate to False.
  • Using float() as the number validator: Lets "nan" slip through (where float("nan") != 250.0 evaluates not_equals to True!) and silently rounds high-precision decimals.
  • Allowing ordering operators (greater_than, less_than) on text fields: Silently runs alphabetical comparisons when a form designer misconfigured a field's type.
  • Accepting empty groups ({"all": []} or {"any": []}): Python's built-in all([]) returns True, silently making a broken condition always show the field.
  • Designing an infix string DSL ("a == 'x' AND b > 10 OR c >= 50"): Forces form designers to memorize operator precedence and requires writing a tokenizer and parser instead of leveraging JSON nesting.
  • Making not_equals return True for unanswered fields: Breaks compatibility with forms where unanswered fields never satisfy visibility conditions.

Alternative approaches

  • Explicit operator tag on groups ({"op": "and", "conditions": [...]}): Equally expressive and dispatches on a single "op" field, though slightly more verbose than {"all": [...]} / {"any": [...]}.
  • Per-type strategy classes (TextQuestionType, NumberQuestionType): Encapsulating parse_answer, parse_condition_value, and allowed_operators in a class per type pays off once a system grows to 5+ types (dates, multi-selects, currencies); for two types, OPERATORS plus parse_number stays concise and clear.

Follow-up questions

  • How could you support negation (not), set membership (in), and range checks (between) while keeping existing operator evaluation untouched? Replace the if/elif chain in evaluate_leaf with an operator registry dictionary mapping each operator name to (allowed_types, parse_rule_value, compare_fn). Existing operators become standalone entries in that registry, while in (accepting a non-empty list of strings parsed via the target field's parser and testing membership) and between (accepting [low, high] with low <= high checked at load time and testing low <= answer <= high) plug in as new registry entries without modifying existing comparisons. For not, add {"not": child_condition} as a unary group node alongside "all" and "any", documenting clearly whether not around an unanswered leaf should invert False to True or stay False.
  • When a form designer introduces a schema error buried several levels inside boolean groups, how can validation pinpoint the exact offending node? Pass a location breadcrumb string where down each recursive call in parse_condition, appending .all[i] or .any[i] at every list index (for example, question 'customs_broker': condition.any[0].all[1]: missing 'operator'). That pinpoints the exact question, group branch, and failing check immediately. In a visual form editor or API, you can also return a JSON Pointer — a slash-delimited path like /questions/2/condition/any/0/all/1 — and accumulate all validation errors in a list rather than stopping at the first error.
  • If a form contains thousands of fields and a user edits a single response, how do you recompute visibility incrementally instead of scanning every rule? At load time, build a reverse dependency index dependents[question_id] listing every question whose condition tree references question_id. When a user edits field X, re-parse only X's response and re-evaluate only the questions in dependents[X], updating a cached visibility set in time proportional to the rules mentioning X. If product semantics ever changed so hiding a field also suppressed its stored answer, visibility updates could cascade forward; because conditions only reference earlier fields, dependencies form a directed acyclic graph (DAG) (a directed graph with no cycles), so processing affected fields in a min-heap ordered by question index still visits each affected field at most once.
  • How could static analysis flag unsatisfiable visibility rules, such as requiring the same numeric field to be both above 100 and below 20? For a single all conjunction over one numeric field, convert each inequality into an interval (low, high) with open/closed endpoint flags, intersect the intervals, and check that the intersection is non-empty after excluding not_equals points (noting that decimals are dense, so (20, 20.001) still contains "20.0005"). Across arbitrary nested all/any trees referencing k fields, partition each field's domain using only the threshold constants appearing in that rule (testing each constant, midpoints between adjacent constants, values below the minimum and above the maximum, and "unanswered"). In the worst case across many fields this is exponential because encoding boolean variables via numeric inequalities reduces Boolean satisfiability (SAT) — an NP-complete problem with no known polynomial-time algorithm for deciding whether a logical formula can ever hold — to rule satisfiability, though real form conditions touch so few fields that finite-domain checking runs in microseconds.

Follow-up questions

Similar questions

More ZipHQ interview questions

All 9 ZipHQ questions →