Katkat

Evaluate Piecewise Linear Function

Two SigmaData Scientist · Online Assessment

Last updated

This question tests the ability to efficiently search through sorted interval data and apply linear interpolation to compute the value of a continuous piecewise function at a specific input point.

Problem Description

You are given a piecewise linear function defined by a sequence of points (x_0, y_0), (x_1, y_1), ..., (x_n, y_n), where the x-coordinates are strictly increasing. This defines a continuous function f(x) where segments are connected by straight lines between consecutive points.

Your task is to implement a function evaluate(points, x) that returns the value f(x) for any given x.

  • If x is exactly one of the x_i, return the corresponding y_i.
  • If x is between x_i and x_{i+1}, use linear interpolation: f(x) = y_i + (y_{i+1} - y_i) * (x - x_i) / (x_{i+1} - x_i).
  • If x is outside the range [x_0, x_n], the function is undefined (return None).

Signature

def evaluate(points, x)

Constraints

  • points: A list of tuples (x, y) sorted by x, where len(points) >= 2.
  • x: A float.

Examples

Example 1: points = [(0, 0), (2, 4), (4, 4)], x = 1.0 Output: 2.0 (Midpoint between (0,0) and (2,4))

Example 2: points = [(0, 0), (2, 4), (4, 4)], x = 3.0 Output: 4.0 (Since x is between x=2 and x=4 where y is constant 4)

Edge Cases

  • x matches the first or last point exactly.
  • x is outside the range [x_0, x_n].
  • The slope is zero between two points.

Hints

Hint 1

Since the x-coordinates are sorted, consider using binary search to efficiently find the interval `[x_i, x_{i+1}]` that contains `x`.

Hint 2

The Python module `bisect` can help you locate the insertion point for `x` to identify the boundary indices.

Hint 3

Handle the cases where `x points[-1][0]` explicitly before searching the interior.

Follow-up questions

  • How would you optimize the implementation if you needed to perform thousands of queries (`evaluate` calls) on the same set of points?
  • How would you modify the function if the points were not sorted by x-coordinate?
  • What changes are required if the function is not continuous but instead a step function?