Conditional Form Visibility with Numeric Checks and Nested Groups
Data Structure DesignAuto-graded · 19 test casesLast updated
Decide which questions of a form are visible by parsing typed answers and evaluating validated, nestable all/any conditions with numeric comparisons.
Form Visibility Rules
You are given a form definition and the raw answers a user typed in. Return the IDs of the questions that should be shown, in form order.
Inputs
spec: a dictionary with a key"questions", an ordered list of question objects. Each question has:id: a unique string.type: either"text"or"number".prompt: a string that you can ignore.condition(optional): a rule that decides whether the question is shown.
answers: a dictionary mapping a question ID to the raw string the user entered. Some questions may have no entry. Entries whose ID matches no question are ignored.
Answer parsing
- Text: the parsed answer is the raw string with leading and trailing whitespace removed.
- Number: strip the raw string. The result must be non-empty, must be accepted by
decimal.Decimal, and must be finite (rejectNaNand infinities). The parsed answer is thatDecimal. For example,"10000.01"," -3 "and"1e3"are valid, while"","1,000"and"abc"are not. - Every answer present in
answersfor a question in the form is parsed, whether or not that question ends up visible. If any such answer is invalid (including a non-string raw value for a number question), raiseValueError. - A question's answer counts in conditions even if that question is itself hidden.
Conditions
A condition is either a leaf or a group.
Leaf: a dictionary with exactly the keys question_id, operator and value.
question_idmust name a question that appears earlier in the list than the question carrying the condition.- If the referenced question is
text, the operator must beequalsornot_equals. The answer is compared withvalueas an exact, case-sensitive string comparison, withvalueused as given. - If the referenced question is
number, the operator must be one ofequals,not_equals,greater_than,greater_than_or_equal,less_than,less_than_or_equal. Thevalueis converted withstr(value).strip()and must be a valid finiteDecimalunder the rules above (so JSON numbers and numeric strings both work). Comparison is numeric, not lexical, andDecimal("5") == Decimal("5.0"). - If the referenced question has no answer, the leaf is
False, for every operator includingnot_equals.
Group: a dictionary with exactly one key, either "all" or "any", and no other keys. Its value must be a non-empty list of conditions (leaves or groups, nested to any depth). all is true when every child is true, and any is true when at least one child is true.
Validation
- A question without a
conditionkey, or withconditionset toNone, is always visible. - Every other condition is validated completely, including all nested children, before it is evaluated. Any violation of the rules above raises
ValueError. This covers:- a condition that is not a dictionary;
- a group with both
allandany, or with extra keys; - an empty or non-list group;
- a leaf with missing or extra keys;
- a reference to an unknown or non-earlier question;
- an operator not allowed for the referenced type;
- an invalid numeric
value.
- Duplicate question IDs and question types other than
textornumberalso raiseValueError. - If any error is raised, the function raises, and no partial list is returned.
Return the IDs of visible questions in their original order.
Constraints
- 1 ≤ number of questions ≤ 1000.
- Condition nesting depth is at most 50.
- Numeric values are decimal strings or JSON numbers. Use exact decimal arithmetic, not binary floats.
- Every question has
idandtypefields.
Examples
Example 1
Input: visible_question_ids({'questions': [{'id': 'request_type', 'type': 'text', 'prompt': 'What are you requesting?'}, {'id': 'justification', 'type': 'text', 'prompt': 'Why is it needed?', 'condition': {'question_id': 'request_type', 'operator': 'equals', 'value': 'software'}}]}, {'request_type': ' software '})
Output: ['request_type', 'justification']
Example 2
Input: visible_question_ids({'questions': [{'id': 'amount', 'type': 'number', 'prompt': 'Amount'}, {'id': 'approval', 'type': 'text', 'prompt': 'Approval required?', 'condition': {'question_id': 'amount', 'operator': 'greater_than', 'value': '10000'}}]}, {'amount': '10000.01'})
Output: ['amount', 'approval']
Example 3
Input: visible_question_ids({'questions': [{'id': 'request_type', 'type': 'text', 'prompt': 'Type'}, {'id': 'amount', 'type': 'number', 'prompt': 'Amount'}, {'id': 'approver', 'type': 'text', 'prompt': 'Approver', 'condition': {'any': [{'all': [{'question_id': 'request_type', 'operator': 'equals', 'value': 'software'}, {'question_id': 'amount', 'operator': 'greater_than', 'value': '10000'}]}, {'question_id': 'amount', 'operator': 'greater_than_or_equal', 'value': '50000'}]}}]}, {'request_type': 'software', 'amount': '12000'})
Output: ['request_type', 'amount', 'approver']
Hints
Hint 1
Parse all provided answers up front into typed values (stripped string or Decimal), raising ValueError on bad numeric input, and keep a lookup from question id to its type and position.
Hint 2
Write a recursive validator for conditions: groups check their key and non-empty list and recurse, leaves check keys, earlier-reference, and operator-versus-type rules, including that numeric values parse as finite Decimals.
Hint 3
Write a recursive evaluator mirroring the validator: all/any over children, and leaves that return False when the referenced answer is missing, otherwise compare with the right operator using Decimal for numbers.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution works in three stages.
-
Index and parse. Walk the questions once. Reject duplicate IDs and unknown types, and record each question's type and position. If the user supplied an answer for that question, parse it right away. Text answers are stripped. Number answers are stripped and converted to a finite
Decimal, and any failure raisesValueError. Parsing every supplied answer up front means that bad numeric input is always reported, even for hidden questions. -
Validate each condition recursively. A group must have exactly one key (
allorany) whose value is a non-empty list, and each child is validated the same way. A leaf must have exactly the three expected keys, must reference an earlier question, and must use an operator permitted for the referenced question's type. For number questions, the condition value must also parse as a finiteDecimal. Validation covers the whole condition tree before evaluation, so a malformed branch raises even if short-circuiting would never reach it. -
Evaluate recursively.
allandanymap to Python'sallandanyover their children. A leaf returnsFalsewhen the referenced question is unanswered. Otherwise it compares the parsed answer with the target: aDecimalfor numbers, the raw string for text. The result is the list of visible IDs in form order.
Why it is correct
- Using
Decimalmakes comparisons exact and numeric. For example,10000.01 > 10000, and5equals5.0, which a lexical or float comparison could get wrong. - Requiring references to earlier questions guarantees conditions depend only on questions that come before them. Hidden questions' answers still count, as the rules specify.
- Validating before evaluating makes error behavior independent of the answers supplied.
- Groups are evaluated by composing the same leaf evaluator, so any nesting depth works and existing single-leaf conditions remain valid.
Complexity
Let n be the number of questions and C the total size of all condition trees. Parsing takes O(n) and validation plus evaluation take O(C). Space is O(n) for the indexes and parsed answers, plus O(depth) for recursion.
Reference solution
from decimal import Decimal, InvalidOperation
from typing import Dict, List
def visible_question_ids(spec: Dict, answers: Dict[str, str]) -> List[str]:
questions = spec["questions"]
by_id = {}
position = {}
parsed = {}
for index, q in enumerate(questions):
qid = q["id"]
if qid in by_id:
raise ValueError(f"duplicate question id: {qid}")
if q["type"] not in ("text", "number"):
raise ValueError(f"unsupported question type: {q['type']}")
by_id[qid] = q
position[qid] = index
if qid not in answers:
continue
raw = answers[qid]
if q["type"] == "text":
parsed[qid] = raw.strip()
else:
try:
text = raw.strip()
if not text:
raise InvalidOperation
value = Decimal(text)
if not value.is_finite():
raise InvalidOperation
parsed[qid] = value
except (AttributeError, InvalidOperation, ValueError):
raise ValueError(f"invalid number answer for {qid}: {raw!r}")
def validate(cond, current_index):
if not isinstance(cond, dict):
raise ValueError("condition must be an object")
group_keys = [k for k in ("all", "any") if k in cond]
if group_keys:
if len(group_keys) != 1 or len(cond) != 1:
raise ValueError("a group must contain exactly one of 'all' or 'any'")
key = group_keys[0]
children = cond[key]
if not isinstance(children, list) or not children:
raise ValueError(f"'{key}' must be a non-empty list")
for child in children:
validate(child, current_index)
return
if set(cond) != {"question_id", "operator", "value"}:
raise ValueError("leaf condition must have question_id, operator, and value")
ref = cond["question_id"]
if ref not in by_id or position[ref] >= current_index:
raise ValueError("conditions must reference an earlier question")
qtype = by_id[ref]["type"]
allowed = {"equals", "not_equals"}
if qtype == "number":
allowed |= {"greater_than", "greater_than_or_equal",
"less_than", "less_than_or_equal"}
try:
target = Decimal(str(cond["value"]).strip())
if not target.is_finite():
raise InvalidOperation
except (InvalidOperation, ValueError):
raise ValueError("numeric condition value must be a valid number")
if cond["operator"] not in allowed:
raise ValueError(f"unsupported operator for {qtype}: {cond['operator']}")
def evaluate(cond):
if "all" in cond:
return all(evaluate(c) for c in cond["all"])
if "any" in cond:
return any(evaluate(c) for c in cond["any"])
qid = cond["question_id"]
if qid not in parsed:
return False
answer = parsed[qid]
op = cond["operator"]
if by_id[qid]["type"] == "number":
target = Decimal(str(cond["value"]).strip())
else:
target = cond["value"]
if op == "equals":
return answer == target
if op == "not_equals":
return answer != target
if op == "greater_than":
return answer > target
if op == "greater_than_or_equal":
return answer >= target
if op == "less_than":
return answer < target
if op == "less_than_or_equal":
return answer <= target
raise ValueError(f"unsupported operator: {op}")
result = []
for index, question in enumerate(questions):
cond = question.get("condition")
if cond is None:
result.append(question["id"])
continue
validate(cond, index)
if evaluate(cond):
result.append(question["id"])
return result