Compare commits
2 Commits
a80acb36c3
...
b78ecc077e
| Author | SHA1 | Date | |
|---|---|---|---|
| b78ecc077e | |||
| f06ab4d690 |
@ -20,3 +20,14 @@ def clamp(value: int, low: int, high: int) -> int:
|
||||
|
||||
def clamp_to_byte(value: int) -> int:
|
||||
return max(0, min(255, value))
|
||||
|
||||
|
||||
def median(values: list[float]) -> float:
|
||||
if not values:
|
||||
raise ValueError
|
||||
sorted_values = sorted(values)
|
||||
n = len(sorted_values)
|
||||
mid = n // 2
|
||||
if n % 2 == 1:
|
||||
return sorted_values[mid]
|
||||
return (sorted_values[mid - 1] + sorted_values[mid]) / 2.0
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
import math
|
||||
import unittest
|
||||
|
||||
from src.calculator import clamp
|
||||
from src.calculator import clamp, median
|
||||
|
||||
|
||||
class TestClampFunction(unittest.TestCase):
|
||||
@ -61,3 +61,29 @@ class TestClampFunction(unittest.TestCase):
|
||||
def test_nan_returns_nan(self) -> None:
|
||||
result = clamp(math.nan, 0, 10)
|
||||
self.assertTrue(math.isnan(result))
|
||||
|
||||
|
||||
class TestMedianFunction(unittest.TestCase):
|
||||
|
||||
def test_odd_length_returns_middle_element(self) -> None:
|
||||
self.assertEqual(median([1, 3, 5]), 3)
|
||||
|
||||
def test_even_length_returns_float_average_of_two_middle_values(self) -> None:
|
||||
result = median([1, 2, 3, 4])
|
||||
self.assertIsInstance(result, float)
|
||||
self.assertEqual(result, 2.5)
|
||||
|
||||
def test_single_element_returns_that_element(self) -> None:
|
||||
self.assertEqual(median([7]), 7)
|
||||
|
||||
def test_empty_list_raises_value_error(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
median([])
|
||||
|
||||
def test_unsorted_input_sorts_correctly(self) -> None:
|
||||
self.assertEqual(median([3, 1, 2]), 2)
|
||||
|
||||
def test_unsorted_even_length_returns_float_average(self) -> None:
|
||||
result = median([10, 30, 20, 40])
|
||||
self.assertIsInstance(result, float)
|
||||
self.assertEqual(result, 25.0)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user