Merge pull request 'feat: Add a percentage function to the calculator' (#18) from typosaurus/16-add-a-percentage-function-to-the-calculator into main
Reviewed-on: #18
This commit is contained in:
commit
2ee246fad6
@ -1,6 +1,6 @@
|
|||||||
# retoor <retoor@molodetz.nl>
|
# retoor <retoor@molodetz.nl>
|
||||||
|
|
||||||
from typing import Sequence
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
|
||||||
def add(left: int, right: int) -> int:
|
def add(left: int, right: int) -> int:
|
||||||
@ -32,3 +32,10 @@ def variance(values: Sequence[float]) -> float:
|
|||||||
return sum((x - mean) ** 2 for x in values) / len(values)
|
return sum((x - mean) ** 2 for x in values) / len(values)
|
||||||
|
|
||||||
|
|
||||||
|
def percentage(value: Union[int, float], total: Union[int, float]) -> float:
|
||||||
|
if total == 0:
|
||||||
|
raise ValueError
|
||||||
|
return (value / total) * 100
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
import math
|
import math
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from src.calculator import clamp, variance
|
from src.calculator import clamp, percentage, variance
|
||||||
|
|
||||||
|
|
||||||
class TestClampFunction(unittest.TestCase):
|
class TestClampFunction(unittest.TestCase):
|
||||||
@ -63,6 +63,31 @@ class TestClampFunction(unittest.TestCase):
|
|||||||
self.assertTrue(math.isnan(result))
|
self.assertTrue(math.isnan(result))
|
||||||
|
|
||||||
|
|
||||||
|
class TestPercentageFunction(unittest.TestCase):
|
||||||
|
|
||||||
|
def test_valid_percentage(self) -> None:
|
||||||
|
self.assertEqual(percentage(50, 200), 25.0)
|
||||||
|
|
||||||
|
def test_zero_value(self) -> None:
|
||||||
|
self.assertEqual(percentage(0, 100), 0.0)
|
||||||
|
|
||||||
|
def test_full_value(self) -> None:
|
||||||
|
self.assertEqual(percentage(200, 100), 200.0)
|
||||||
|
|
||||||
|
def test_fractional(self) -> None:
|
||||||
|
self.assertAlmostEqual(percentage(1, 3), 33.333333333333336)
|
||||||
|
|
||||||
|
def test_total_zero(self) -> None:
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
percentage(50, 0)
|
||||||
|
|
||||||
|
def test_float_arguments(self) -> None:
|
||||||
|
self.assertEqual(percentage(25.5, 100.0), 25.5)
|
||||||
|
|
||||||
|
def test_negative_value(self) -> None:
|
||||||
|
self.assertEqual(percentage(-50, 200), -25.0)
|
||||||
|
|
||||||
|
|
||||||
class TestVarianceFunction(unittest.TestCase):
|
class TestVarianceFunction(unittest.TestCase):
|
||||||
|
|
||||||
def test_empty_list_raises_value_error(self) -> None:
|
def test_empty_list_raises_value_error(self) -> None:
|
||||||
@ -94,3 +119,4 @@ class TestVarianceFunction(unittest.TestCase):
|
|||||||
self.assertEqual(variance((1, 2, 3, 4, 5)), 2.0)
|
self.assertEqual(variance((1, 2, 3, 4, 5)), 2.0)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user