From 613a56cc86ff0b0c8d7bf58a0a233c5cc63a7abd Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Tue, 20 Aug 2019 12:50:38 +0300 Subject: [PATCH] Add clamp_number snippet --- snippets/clamp_number.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 snippets/clamp_number.md diff --git a/snippets/clamp_number.md b/snippets/clamp_number.md new file mode 100644 index 000000000..d965655db --- /dev/null +++ b/snippets/clamp_number.md @@ -0,0 +1,19 @@ +--- +title: clamp_number +tags: math,beginner +--- + +Clamps `num` within the inclusive range specified by the boundary values `a` and `b`. + +If `num` falls within the range, return `num`. +Otherwise, return the nearest number in the range. + +```py +def clamp_number(num,a,b): + return max(min(num, max(a,b)),min(a,b)) +``` + +```py +clamp_number(2, 3, 5) # 3 +clamp_number(1, -1, -5) # -1 +```