Skip to content

Commit cf998dc

Browse files
committed
refactor(math, perfect squares): input validation and tests
1 parent 03003e8 commit cf998dc

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

pymath/perfect_square/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Given an integer, n, return the least number of perfect square numbers that sum
77
88
## Constraints
99

10-
- 1 < `n` < 10^3
10+
- 1 <= `n` < 10^3
1111

1212
## Solution
1313

pymath/perfect_square/__init__.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def num_squares(n: int) -> int:
4141
raise ValueError("n must be non-negative")
4242
if n == 0:
4343
return 0
44-
44+
4545
dp = [float("inf")] * (n + 1)
4646
dp[0] = 0
4747

@@ -62,6 +62,11 @@ def num_squares_2(n: int) -> int:
6262
Returns:
6363
int: The least number of perfect square numbers that sum to n.
6464
"""
65+
if n < 0:
66+
raise ValueError("n must be non-negative")
67+
if n == 0:
68+
return 0
69+
6570
# Apply reduction by removing factors of 4
6671
while n % 4 == 0:
6772
n = n // 4

pymath/perfect_square/test_perfect_squares.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import unittest
22
from parameterized import parameterized
3-
from pymath.perfect_square import num_squares
3+
from pymath.perfect_square import num_squares, num_squares_2
44

55

66
TEST_CASES = [
@@ -16,6 +16,10 @@ class NumOfPerfectSquaresTestCases(unittest.TestCase):
1616
@parameterized.expand(TEST_CASES)
1717
def test_num_of_perfect_squares(self, n: int, expected: int):
1818
actual = num_squares(n)
19+
(self.assertEqual(expected, actual) @ parameterized.expand(TEST_CASES))
20+
21+
def test_num_of_perfect_squares_2(self, n: int, expected: int):
22+
actual = num_squares_2(n)
1923
self.assertEqual(expected, actual)
2024

2125

0 commit comments

Comments
 (0)