Files
30-seconds-of-code/snippets/python/s/clamp-number.md
Angelos Chalaris 4d0316a062 Update covers
2023-05-07 22:25:00 +03:00

474 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Clamp number snippet python
math
colorful-rocks 2020-11-02T19:27:07+02:00

Clamps num within the inclusive range specified by the boundary values.

  • If num falls within the range (a, b), return num.
  • Otherwise, return the nearest number in the range.
def clamp_number(num, a, b):
  return max(min(num, max(a, b)), min(a, b))
clamp_number(2, 3, 5) # 3
clamp_number(1, -1, -5) # -1