FreeExam

Tensor and Array Reasoning

Original AI/ML Engineer coding practice on tensor shapes, indexing, contractions, masks, stable reductions, sparse updates and sequence operations. Use Python standard-library code and do not mutate inputs.

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

  1. 1.Infer a rectangular nested shape

    Write nested_shape(value). A number has shape []; a list has its length followed by the common shape of its children. An empty list has shape [0]. Return None if any sibling shapes differ or a descendant is ragged. Inputs contain only numbers and lists.

  2. 2.Resolve two broadcast shapes

    Write broadcast_shape(a, b) for lists of nonnegative dimensions. Align from the right, treating missing dimensions as 1. Equal dimensions stay equal; if one is 1 use the other, including 0. Any other mismatch returns None. Return the resulting dimension list; [] denotes a scalar.

  3. 3.Compute row-major element strides

    Write element_strides(shape) for a list of nonnegative dimensions. The final axis stride is 1; each preceding stride is the product of dimensions to its right. Return [] for scalar shape []. Strides count elements, not bytes; preserve this rule even when a dimension is zero.

  4. 4.Decode a flat element position

    Write unravel_position(index, shape) for positive integer dimensions in row-major order. Return the coordinate list, or None if index is negative or at least the product of dimensions. Shape [] is a scalar with one element, so index 0 returns [].

  5. 5.Encode a coordinate as a flat position

    Write ravel_position(coords, shape) for positive integer dimensions. Return the row-major flat index, or None if ranks differ or any coordinate is negative or outside its dimension. For coords=[] and shape=[], return 0. Do not apply Python negative-index wrapping.

  6. 6.Rebuild a matrix from a flat buffer

    Write reshape_rows(flat, rows), where rows is a positive integer. Return a new row-major matrix with exactly rows rows and equal column counts. Return None if len(flat) is not divisible by rows. Empty flat input produces rows separate empty lists. Do not mutate flat.

  7. 7.Transpose a rectangular matrix

    Write transpose_rows(matrix) for a rectangular list of numeric rows. Return new lists with rows and columns exchanged. The outer list may be empty, and rows may have zero columns; both cases return []. Do not mutate the input or return its existing row objects.

  8. 8.Permute three tensor axes

    Write permute_three(x, axes). x is a nonempty rectangular three-dimensional nested list with all axis lengths positive. axes is a permutation of [0,1,2]; output axis k corresponds to input axis axes[k]. Return the reordered nested lists without mutating x.

  9. 9.Multiply matching matrix batches

    Write batch_product(a, b) for batches shaped B×M×K and B×K×N. All inner dimensions are positive and compatible; both outer lists may instead be empty. Return B×M×N nested lists using ordinary matrix multiplication, pairing only matrices with the same batch index. Empty batches return [].

  10. 10.Apply shared weights on the last axis

    Write linear_rows(x, weights, bias). x has shape B×K, weights has shape N×K, and bias has length N. K and N are positive; B may be zero. Return B×N values y[i][j] = sum(x[i][k] * weights[j][k]) + bias[j]. Do not transpose the meaning of the weight axes.

  11. 11.Reduce only selected row elements

    Write masked_means(rows, masks). rows is rectangular and masks has the same shape with Boolean entries. Return one mean per row, using only entries whose mask is True; an all-False or empty row yields 0.0. Empty outer input returns []. A selected numeric zero still counts in the denominator.

  12. 12.Compute a stable masked softmax

    Write masked_softmax(logits, mask) for equal-length lists of finite numbers and Booleans. Return exp-normalized probabilities over True positions only, with exactly 0.0 at False positions. If nothing is selected, return all zeros. Subtract the selected maximum before exponentiating; large positive logits must work.

  13. 13.Normalize rows with population variance

    Write normalize_features(rows, epsilon). Each row is nonempty and epsilon > 0. For each row independently, compute its mean m and population variance v = mean((x-m)^2), then return (x-m)/sqrt(v+epsilon) per entry. Do not add learned scale or bias. Empty outer input returns []. Values have moderate magnitude.

  14. 14.Scale rows to Euclidean unit length

    Write unit_rows(rows). Each numeric row may be empty. Divide each row by its Euclidean norm sqrt(sum(x*x)); if the norm is zero, return a same-length row of 0.0 values. Empty outer input returns []. Values have moderate magnitude. Return new lists without changing any input row.

  15. 15.Compare every pair of feature rows

    Write cosine_grid(left, right). Rows in both lists have the same positive width and moderate finite values. Return a matrix of dot(a,b)/(norm(a)*norm(b)), one row per left vector and one column per right vector. Define similarity as 0.0 if either norm is zero. Either list may be empty.

  16. 16.Accumulate values into segment slots

    Write segment_totals(values, ids, count). values and ids have equal length; ids are integers and count >= 0. Return count numeric totals, adding each value to the slot named by its id. Ignore ids outside [0,count), including negatives. Keep zero totals for unobserved segments. Do not sort or renumber ids.

  17. 17.Combine repeated sparse coordinates

    Write coalesce_entries(coords, values). coords is a list of nonnegative [row,col] pairs and values has the same length. Sum values at identical coordinates, then return {"coords": ..., "values": ...} sorted by row and then column. Keep coordinates whose combined value is zero. Empty input returns two empty lists.

  18. 18.Scatter repeated updates into a copy

    Write scatter_updates(base, indices, updates). indices and updates have equal length and integer indices. Return a copy of base with each update added at its index, accumulating repeated indices. Ignore indices outside [0,len(base)), including negatives. Do not change base, indices or updates.

  19. 19.Gather independent row copies

    Write gather_copies(matrix, indices). Return one entry per integer index: a fresh copy of matrix[index] when 0 <= index < len(matrix), otherwise None. Repeated valid indices produce separate row lists. Empty rows are valid. Do not mutate matrix; negative indices must not wrap.

  20. 20.Select columns separately for each row

    Write gather_columns(rows, indices). indices has one integer-index list per row. For each row, gather values at its corresponding indices in order; an index outside that row, including a negative one, produces None. Rows may have different lengths, and each selection list may have a different length.

  21. 21.Extract complete strided windows

    Write complete_windows(values, width, step), with positive integer width and step. Return copies of every full window values[start:start+width] for starts 0, step, 2*step, ... whose entire window fits. Drop incomplete trailing windows; do not pad or mutate the input.

  22. 22.Apply a dilated one-dimensional kernel

    Write dilated_correlation(signal, kernel, dilation). kernel is nonempty and dilation is a positive integer. At every valid start s, output sum(signal[s+j*dilation]*kernel[j]). Advance starts by 1, do not reverse the kernel, and do not pad. Return [] when its span exceeds the signal length.

  23. 23.Pool maxima and their original indices

    Write pool_maxima(values, width, step) for positive width and step. At starts 0, step, ... keep only complete windows. Return {"values": maxima, "indices": absolute_indices}, choosing the smallest absolute index when a window has tied maxima. No full window yields two empty lists.

  24. 24.Flatten image patches in spatial order

    Write image_patches(image, height, width, step). image is a nonempty rectangular numeric matrix; the three size arguments are positive integers. Visit full patches at top-left coordinates (r,c), with each axis starting at 0 and advancing by step, row first. Return each patch flattened in row-major order. Do not pad.

  25. 25.Reconstruct variable-length rows

    Write unpack_lengths(flat, lengths). lengths contains nonnegative integers whose sum equals len(flat). Return consecutive copied slices of flat with those lengths, in order, retaining zero-length rows. Empty lengths returns []. Do not infer boundaries from values or mutate either input.

  26. 26.Pack selected entries with row boundaries

    Write pack_selected(rows, masks) for numeric rows and same-shaped Boolean masks. Return {"values": selected entries in row-major order, "splits": cumulative selected counts beginning with 0 and ending after each row}. Keep a split for rows selecting nothing. Empty outer input has splits [0].

  27. 27.Accumulate prefixes through masked rows

    Write masked_prefix(rows, masks) for numeric rows and same-shaped Boolean masks. Process each row left to right with a sum starting at zero. A True position adds its value and outputs the new sum. A False position outputs 0 but leaves the running sum unchanged. Start a separate sum for every row.

  28. 28.Compute weighted feature means

    Write weighted_columns(rows, weights). rows is rectangular, weights has one nonnegative number per row, and all values have moderate magnitude. Return a weighted mean for each column, dividing by the sum of weights. If that sum is zero, return a zero vector of the column width. Empty outer input returns [].

  29. 29.Assemble independent matrix blocks

    Write block_diagonal(blocks). Every block is a nonempty rectangular numeric matrix with positive width. Return one matrix placing the blocks along the diagonal in order, with zero in every off-block position. Blocks may have different heights and widths. Empty blocks input returns []. Do not mutate the blocks.

  30. 30.Rotate adjacent feature pairs

    Write rotate_pairs(rows, angles). Every row has width 2*len(angles); angles are radians. For pair (x,y) at positions 2j and 2j+1, output (x*cos(a)-y*sin(a), x*sin(a)+y*cos(a)), using a=angles[j]. Apply the same angles to each row. Empty rows and empty outer input are allowed. Do not mutate inputs.