Four Utility Functions: Crop, Softmax, Gaussian, Triangle
Arrays & HashingAuto-graded · 19 test casesLast updated
Tests array slicing, numerical stability in exponential calculations, 2D kernel generation, and geometric inequality validation in a single bundled function.
Problem Statement
Implement a function that performs four distinct computational tasks and returns their results in a dictionary. Each task addresses a common pattern in data processing and algorithm implementation.
Task Specifications
Your function receives seven parameters and must return a dictionary with exactly four keys: "center_crop", "softmax", "gaussian_kernel", and "valid_triangle".
Task 1: Center Crop
Extract the central region of a 3D nested list representing an image.
- Input:
imageis a nested list with shape(H, W, C)where each pixel location contains a list of channel values. You also receive target dimensionsnew_handnew_w. - Output: Return the center-cropped region of size
(new_h, new_w, C)as a nested list. - Behavior: Calculate the top-left corner of the crop using integer division:
row_offset = (H - new_h) // 2andcol_offset = (W - new_w) // 2. Extract rows fromrow_offsettorow_offset + new_h - 1(inclusive), and within each row, extract columns fromcol_offsettocol_offset + new_w - 1(inclusive).
Task 2: Numerically Stable Softmax
Compute the softmax transformation of a 1D list.
- Input:
xis a list of floats. - Output: Return a list of the same length where each element is
exp(x[i] - max_val) / sum_of_all_exponentials, withmax_val = max(x). - Behavior: Subtracting the maximum value before exponentiation prevents overflow on large inputs. If
xis empty, return an empty list.
Task 3: 2D Gaussian Kernel
Generate a square Gaussian kernel normalized to sum to 1.
- Input:
k(kernel size) andsigma(standard deviation). - Output: Return a
k × knested list representing the kernel. - Behavior: Define the kernel center at coordinate
center = (k - 1) / 2.0. For each position(row, col), compute the value asexp(-distance_squared / (2 * sigma^2))wheredistance_squared = (row - center)^2 + (col - center)^2. After computing all values, divide each by the total sum so the kernel sums to exactly 1.
Task 4: Valid Triangle Check
Determine whether three side lengths can form a non-degenerate triangle.
- Input:
sidesis a list of floats. - Output: Return
Trueif the sides form a valid triangle, otherwiseFalse. - Behavior: A valid triangle requires exactly three sides, all strictly positive, where the sum of any two sides is strictly greater than the third. Checking only the smallest two sides against the largest is sufficient: if
a ≤ b ≤ c, verifya + b > c.
Constraints
1 ≤ H, W ≤ 10001 ≤ new_h ≤ Hand1 ≤ new_w ≤ W0 ≤ len(x) ≤ 1000-10000 ≤ x[i] ≤ 100001 ≤ k ≤ 1000.1 ≤ sigma ≤ 100 ≤ len(sides) ≤ 10- All numeric inputs are valid (no NaN or infinity)
Examples
Example 1
Input: compute_four_tasks([[0, 1, 2], [3, 4, 5], [6, 7, 8]], 2, 2, [1000, 1001], 3, 1, [3, 4, 5])
Output: {'center_crop': [[0, 1], [3, 4]], 'softmax': [0.2689414213699951, 0.7310585786300049], 'gaussian_kernel': [[0.07511360795411151, 0.12384140315297397, 0.07511360795411151], [0.12384140315297397, 0.2041799555716581, 0.12384140315297397], [0.07511360795411151, 0.12384140315297397, 0.07511360795411151]], 'valid_triangle': True}
Example 2
Input: compute_four_tasks([[1, 2], [3, 4]], 1, 1, [0, 0], 1, 2, [1, 1, 3])
Output: {'center_crop': [[1]], 'softmax': [0.5, 0.5], 'gaussian_kernel': [[1]], 'valid_triangle': False}
Example 3
Input: compute_four_tasks([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 3, 2, [-1000, 0, 1000], 5, 0.5, [2, 2, 3])
Output: {'center_crop': [[2, 3], [6, 7], [10, 11]], 'softmax': [0, 0, 1], 'gaussian_kernel': [[6.962478188799074e-8, 0.000028088641754266942, 0.00020754854966504427, 0.000028088641754266942, 6.962478188799074e-8], [0.000028088641754266942, 0.011331766853773574, 0.08373106098253583, 0.011331766853773574, 0.000028088641754266942], [0.00020754854966504427, 0.08373106098253583, 0.6186935068229404, 0.08373106098253583, 0.00020754854966504427], [0.000028088641754266942, 0.011331766853773574, 0.08373106098253583, 0.011331766853773574, 0.000028088641754266942], [6.962478188799074e-8, 0.000028088641754266942, 0.00020754854966504427, 0.000028088641754266942, 6.962478188799074e-8]], 'valid_triangle': True}
Hints
Hint 1
For the crop, use integer division to find the starting indices, handling any odd remainder by placing it on the bottom/right edges.
Hint 2
Softmax stability: subtract max(x) before computing exponentials to prevent overflow while preserving the mathematical result.
Hint 3
The Gaussian kernel center at (k-1)/2 ensures symmetry for both odd and even k; normalize by dividing all entries by their sum.
Hint 4
For triangle validation, sort the three sides first—then you only need to check whether the two smallest sum to more than the largest.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem bundles four independent tasks into a single function that returns a dictionary. Each task tests a different computational skill.
Task 1: Center Crop
Calculate the starting row and column using integer division to center the crop region. Any odd remainder pixels are implicitly placed on the bottom and right edges. Extract the target rows, and within each row, slice out the target columns. The channel dimension is preserved automatically since each pixel is a list that gets copied during the slice.
Task 2: Stable Softmax
The standard softmax formula exp(x[i]) / sum(exp(x[j])) overflows when values are large (e.g., 1000). The key insight is that softmax(x) = softmax(x - c) for any constant c, because the factor exp(-c) cancels between numerator and denominator. By choosing c = max(x), the largest exponent becomes exp(0) = 1, preventing overflow. The denominator is at least 1, preventing division by zero. Handle the empty list case explicitly.
Task 3: Gaussian Kernel
Define the center at (k-1)/2, which places it at the middle cell for odd k and between cells for even k. For each position, compute the squared Euclidean distance from the center and apply the Gaussian formula exp(-distance² / (2σ²)). The 1/(2πσ²) normalization constant is omitted because we explicitly normalize by dividing all values by their sum afterward. This ensures the kernel sums to exactly 1 regardless of k or sigma.
Task 4: Triangle Check
A valid triangle requires exactly three sides, all positive, satisfying the triangle inequality: the sum of any two sides must exceed the third. By sorting the sides as a ≤ b ≤ c, we only need to verify a + b > c. The other inequalities (a + c > b and b + c > a) automatically hold since c ≥ b and a > 0. Using strict inequality > (not ≥) correctly rejects degenerate triangles like [1, 2, 3].
Why It Works
- Crop: Integer division floors the offset, placing any odd pixel on the far edge. For
H=5, new_h=2, the offset is(5-2)//2 = 1, extracting rows 1-2 (zero-indexed), which is centered. - Softmax: The shift preserves the mathematical result exactly while keeping all intermediate values in safe numerical ranges.
- Gaussian: Squared distance from a fractional center produces a symmetric kernel. Explicit normalization guarantees the sum is 1.
- Triangle: The sorted check is both necessary and sufficient for the triangle inequality.
Complexity
- Center crop: O(new_h × new_w) time and space to construct the output.
- Softmax: O(n) time for three passes (max, exponentials, sum), O(n) space.
- Gaussian kernel: O(k²) time and space.
- Triangle check: O(1) time (sorting three elements is constant).
Overall: O(new_h × new_w + n + k²) time, dominated by whichever dimension is largest.
Solution Code
import math
from typing import List, Dict
def compute_four_tasks(image: List[List[List[float]]], new_h: int, new_w: int,
x: List[float], k: int, sigma: float,
sides: List[float]) -> Dict[str, object]:
# Task 1: Center crop
h = len(image)
w = len(image[0]) if h else 0
row_offset = (h - new_h) // 2
col_offset = (w - new_w) // 2
cropped = [list(image[r][col_offset:col_offset + new_w])
for r in range(row_offset, row_offset + new_h)]
# Task 2: Numerically stable softmax
if not x:
softmax_result = []
else:
max_val = max(x)
exp_values = [math.exp(val - max_val) for val in x]
total = sum(exp_values)
softmax_result = [val / total for val in exp_values]
# Task 3: Normalized 2D Gaussian kernel
center = (k - 1) / 2.0
kernel = []
for r in range(k):
row_values = []
for c in range(k):
dist_sq = (r - center) ** 2 + (c - center) ** 2
row_values.append(math.exp(-dist_sq / (2.0 * sigma * sigma)))
kernel.append(row_values)
total_sum = sum(sum(row) for row in kernel)
kernel = [[val / total_sum for val in row] for row in kernel]
# Task 4: Triangle validity check
is_valid = False
if len(sides) == 3 and all(s > 0 for s in sides):
sorted_sides = sorted(sides)
is_valid = sorted_sides[0] + sorted_sides[1] > sorted_sides[2]
return {
"center_crop": cropped,
"softmax": softmax_result,
"gaussian_kernel": kernel,
"valid_triangle": is_valid,
}