Skip to content
ExamSpine

Lesson 4.4 · Write it

Clamp a value

A functionPython or Java8 tests, 5 of them hidden

On a phone? Put the lines in order instead

Write a function that clamps a value into a range: if it is below the low end, return the low end; if it is above the high end, return the high end; otherwise return the value unchanged.

  1. value, low and high are whole numbers.
  2. low is always less than or equal to high.
  3. If value is less than low, return low.
  4. If value is greater than high, return high.
  5. Otherwise, return value unchanged.

Only the number your function returns is checked.

def clamp(value: int, low: int, high: int) -> int

Examples

Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.

  • clamp(5, 1, 10) should return 5: value is in range, returned unchanged (rule 5)
  • clamp(-3, 0, 100) should return 0: value is below low, return low (rule 3)
  • clamp(150, 0, 100) should return 100: value is above high, return high (rule 4)

public static int clamp(int value, int low, int high)

Checking whether Java answers can run here.

Examples

Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.

  • clamp(5, 1, 10) should return 5: value is in range, returned unchanged (rule 5)
  • clamp(-3, 0, 100) should return 0: value is below low, return low (rule 3)
  • clamp(150, 0, 100) should return 100: value is above high, return high (rule 4)
solution.pySolution.java