FreeExam

Parsing and Structured Data

Thirty original Python problems on explicit token grammars, exact expressions, typed tree paths, atomic edits, grammar ambiguity, lexical bindings and structured records. Preserve empty and missing support, complete syntax, failure evidence and detached results.

These problems are original practice. They are not questions from a named employer or a live hiring loop.

  1. 1.Scan token spans before the first unsupported character

    Write scan_tokens(text,symbols), distinct nonempty symbol strings. Skip ASCII space/tab/CR/LF. Prefer ASCII identifier [A-Za-z_][A-Za-z_0-9]*, then ASCII digit run, then longest matching symbol (lexical tie). Return [tokens,error_offset_or_None], tokens [kind,raw,start,end], kind id/int/sym; offsets are code points, end exclusive. Stop at first unsupported character; retain prefix. No mutation.

  2. 2.Split fields while decoding a strict escape vocabulary

    Write escaped_fields(text). Unescaped | separates fields, preserving empty/trailing fields. Backslash escapes ONLY |, backslash, n and t, yielding literal |, backslash, newline and tab. Other characters, including quotes, are literal. Invalid escape or trailing backslash returns None; otherwise return fields. Empty text gives one empty field. No mutation.

  3. 3.Consume counted payloads without delimiter guessing

    Write length_frames(text), concatenated frames LENGTH:PAYLOAD. LENGTH is ASCII decimal, at least one digit, with no leading zero unless exactly 0. It counts Unicode code points of PAYLOAD; payload may contain colons, digits or newlines. No whitespace outside payload. Return payload strings, or None for any malformed/truncated frame or trailing garbage. Empty input returns [].

  4. 4.Parse one complete labeled tree with explicit empty children

    Write labeled_tree(text). Grammar: node = ( LABEL : node* ), with literal parentheses/colon and LABEL one or more ASCII lowercase letters. No whitespace or other characters allowed. Return [label,children] for exactly ONE complete node, or None if invalid. Leaf example (a:) has children []. Consume all text; sibling roots are invalid.

  5. 5.Parse nested integer lists with canonical number spellings

    Write integer_lists(text). A value is an ASCII integer or [comma-separated values], allowing empty lists. Integers: optional minus then digits, no leading zeros, and -0 forbidden. ASCII space/tab/CR/LF allowed between tokens only. No plus sign or trailing comma. Return the nested integer/list value, or None for invalid or extra input. Empty text is invalid.

  6. 6.Evaluate arithmetic with unary minus and exact fractions

    Write exact_expression(text), ASCII nonnegative digit runs, binary + - * /, unary minus and parentheses. Usual precedence: unary minus, then * /, then + -; binary operators associate left. ASCII whitespace allowed between tokens. Require one full expression; no unary plus or implicit multiplication. Return reduced [numerator,positive_denominator], or None for syntax error/division by zero.

  7. 7.Build operand-ordered postfix trees with peak stack evidence

    Write postfix_tree(tokens), strings that are canonical ASCII integer spellings (str(int(token))==token) or binary + - *. Each operator pops RIGHT then LEFT and pushes [operator,left,right]; integers are leaf ints. Return [tree,maximum_stack_size], or None for invalid token, underflow, empty input or more than one final tree. No mutation.

  8. 8.Build an outline without skipping indentation levels

    Write outline(lines), strings with leading ASCII spaces then nonempty label. Tabs invalid. Depth is leading spaces/2, requiring even count. First line must have depth 0; depth can increase by at most one from previous line. Return ordered forest [label,children] nodes, or None for invalid input. Labels retain all nonleading characters. Empty lines invalid; empty input gives []. No mutation.

  9. 9.Reduce tagged events while merging adjacent text children

    Write tag_forest(events): [open,name,attribute_pairs], [text,string], [close,name]. Names/attribute keys/values strings. Build forest nodes [name,attribute_dict,children]; text children strings. Require balanced matching names and unique attributes per open. Text only inside a node; ignore empty text and merge adjacent text children. Any invalid/unclosed event sequence => None. No mutation.

  10. 10.Select wildcard paths while preserving absent and null

    Write select_paths(tree,path), JSON tree, integer numbers. Steps [key,string], [index,nonnegative_int], or [all]. key requires dict; index requires in-range list; all visits dict keys sorted or list indices ascending, scalar none. Missing branches vanish. Return [typed_path,deep_copied_value] matches in traversal order; typed path uses key/index steps. Empty path selects root. No mutation.

  11. 11.Flatten typed paths while preserving empty containers

    Write leaf_rows(tree), JSON tree with integer numbers. Recurse dict keys sorted and list indices ascending. Emit [typed_path,deep_copied_value] at every scalar OR empty dict/list; nonempty containers themselves emit nothing. Path steps [key,string] or [index,integer]. Root leaf path []. Preserve bool/int/null and empty container distinctions. No mutation.

  12. 12.Reconstruct dense typed paths without prefix conflicts

    Write rebuild_rows(rows), [typed_path,leaf_value], leaves scalars or empty dict/list, JSON integer numbers. Steps [key,string] or [index,nonnegative_int]. Reject duplicate paths, prefix overlap, mixed key/index children, or nondense arrays (must be 0..n-1). Empty rows invalid. Return [True,detached_tree] or [False,None]. Rows may arrive in any order. No mutation.

  13. 13.Apply typed tree patches with full rollback and error index

    Write atomic_patch(tree,ops), JSON integer trees. Ops [set,path,value], [remove,path], [test,path,value]; typed key/index paths. Dict set may add; list set/remove needs existing index; parents must exist. Root set/test allowed, root remove invalid. Test uses typed structural equality. Stop on first failure: [False,original_copy,index]; success [True,edited_copy,None]. Deep detach. No mutation.

  14. 14.Encode typed structure with sorted keys and counted strings

    Write encode_tree(value), JSON tree, numbers integers. Encode None as n, bool as t/f, int as iDECIMAL; and string as sLENGTH:TEXT, length in Unicode code points. List: [ concatenated element encodings ]; dict: { concatenated encoded_key=encoded_value pairs in sorted key order }. No added spaces/commas. Return string. Preserve empty structures and exact types. No mutation.

  15. 15.Report minimal changed paths in deterministic traversal

    Write changed_paths(before,after), JSON trees with integer numbers. Unequal types or scalars emit current typed path. Equal dicts compare sorted union keys: missing key emits that key path, present keys recurse. Lists recurse shared indices then emit each extra tail index. Equal subtrees emit nothing. Steps key/index; root path []. Return paths in this traversal order. No mutation.

  16. 16.Intern typed subtrees with stable postorder identities

    Write intern_tree(tree), JSON integer tree. Visit dict keys sorted, list children in order, then node. First structurally equal TYPED subtree gets next ID (0-based); later equal subtrees reuse it. Return [root_ID,nodes], each node [kind,payload], kind null/bool/int/str/list/dict; list payload child IDs, dict payload sorted [key,child_ID], scalar payload original value. Deep detach. No mutation.

  17. 17.Expand only exact reference markers with detached copies

    Write expand_refs(definitions,name), named JSON integer trees. A dict with EXACTLY sole key $ and string value is a reference to that definition; other dicts literal but their values recurse. Expand from name; missing reachable definition or reference cycle => [False,None]. Ignore unreachable bad definitions. Success [True,expanded_tree], including null. Deep detach occurrences. No mutation.

  18. 18.Count grammar parses including ambiguous empty splits

    Write grammar_count(rules,start,tokens). rules[name] lists productions; each production a list [lit,token] or [ref,declared_name] symbols. Rule-reference graph is acyclic. Empty production yields empty token list. Count all parse trees deriving EXACT tokens; repeated production occurrences count separately. Return integer count, 0 if none. No mutation.

  19. 19.Count segmentations and choose cost before lexical words

    Write segment_words(text,costs), dict nonempty word->integer cost. Segment entire text into dictionary words; word occurrences may repeat. Return [number_of_segmentations,minimum_total_cost,lexical_smallest_word_list_at_that_cost]. No segmentations => [0,None,None]; empty text => [1,0,[]]. Negative costs allowed; nonempty words make every segmentation finite. No mutation.

  20. 20.Resolve lexical names with same-scope duplicate rejection

    Write scoped_reads(events): [enter], [leave], [let,name,JSON_value], [use,name], JSON numbers integers. Begin root scope; enter pushes, leave rejects at root. let rejects same-scope duplicates; outer shadowing allowed. use searches nearest scope. Return [reads,rejected_indices], reads [event_index,found,value_or_None,scope_distance_or_None]. Deep detach. Open scopes at end allowed. No mutation.

  21. 21.Count free uses and locate unused binders under shadowing

    Write binding_report(ast), valid nodes [lit,value], [var,name], [pair,left,right], [bind,name,value_expr,body]. A binder scopes only its body, not its value expression; nearest binder wins. Return [sorted [free_name,occurrence_count],sorted_unused_binder_paths]. Paths are AST list indices to bind nodes, root []. A binder used only under a shadowing binder is unused. No mutation.

  22. 22.Normalize arithmetic ASTs into dense canonical coefficients

    Write polynomial(ast), valid nodes integer, [var], [neg,expr], [add,left,right], [mul,left,right]. Interpret one indeterminate x and integer arithmetic. Return dense coefficient list [constant,x_coefficient,...], dropping trailing zeros; zero polynomial is [0]. Nodes need no simplification beforehand. No mutation.

  23. 23.Evaluate structured predicates with explicit unknown support

    Write filter_rows(rows,query), JSON-scalar field maps, numbers integers. Query [exists,key], [eq,key,value], [lt,key,int], [not,q], [and,a,b], [or,a,b]. Missing comparison => unknown; eq type-sensitive, lt only nonbool ints else unknown. not unknown=unknown; and False wins else unknown wins; or True wins else unknown wins. Return [true_row_indices,unknown_row_indices]. No mutation.

  24. 24.Parse block records with owned continuation lines

    Write record_blocks(lines), lines without embedded newlines. Empty line ends a record; repeated empties ignored. Other line is KEY=VALUE (KEY nonempty ASCII lowercase), or starts one space: append newline plus remaining text to most recent key of current record. Values otherwise literal, including =. Duplicate key per record, invalid key or orphan continuation => None. Return records. No mutation.

  25. 25.Expand cell spans from each row's first free anchor

    Write span_grid(width,rows), integer width>=0; each row lists [string_label,positive_colspan,positive_rowspan]. In row order each cell anchors at LOWEST unfilled column; its whole rectangle must fit the grid and be unfilled, otherwise None (do not skip a blocked rectangle). Every grid cell must be filled. Return label matrix. Rows may be empty if earlier spans cover them. No mutation.

  26. 26.Match complete paths with single and repeated wildcards

    Write matching_paths(paths,pattern), lists of string segments. Literal pattern token matches itself; * matches exactly one segment; ** matches zero or more. Match WHOLE path. Return matching input indices in original order, retaining duplicate paths. Adjacent ** tokens allowed; other strings, including ***, are literal. Empty pattern matches only empty path. No mutation.

  27. 27.Pair detached leaves or report the first shape disagreement

    Write align_trees(left,right), JSON integer trees. Dict shapes require same keys, checked sorted union; list shapes require same length, checked index order, extra tail mismatch at first extra index. Container/scalar kind mismatch reports current path; any two scalars pair regardless of type. Return [True,paired_tree,None], or [False,None,first_typed_error_path]. Deep detach; no mutation.

  28. 28.Build complete parent-linked forests with sibling ordering

    Write hierarchy(rows), [unique_string_id,parent_id_or_None,integer_position,JSON_value], numbers integers. Parent must be declared; reject cycles, including components unreachable from roots. Return forest nodes [id,detached_value,children], roots/siblings sorted by (position,id), or None if invalid. Input order arbitrary; duplicate positions allowed. Empty rows gives []. No mutation.

  29. 29.Apply original-coordinate splices without deletion overlap

    Write splice_snapshot(values,edits), edits [start,delete_count,insert_list], integer start/count>=0 and start+count<=len(values). Coordinates use ORIGINAL list. Positive deletion ranges may touch, never overlap. Any edit start strictly inside another deletion invalid. Emit inserts per start in input order, then retain undeleted originals. Return [True,detached_result] or [False,None]. No mutation.

  30. 30.Reduce structured tokens with exact first-error positions

    Write reduce_tokens(events): [array], [end_array], [object], [end_object], [key,string], [value,JSON_scalar] (numbers integers). One root; arrays take values, objects alternate unique keys and values. Closed containers count. Wrong close, misplaced key/value, duplicate key or extra root => [False,None,event_index]. Incomplete/empty EOF uses len(events). Success [True,tree,None]. No mutation.