Skip to content

Commit 31e6b27

Browse files
committed
fix(maths): use specific exception types in collatz_sequence
Replace generic Exception with TypeError for non-integer inputs and ValueError for non-positive integers. Split the combined validation check into two separate checks for clearer error reporting. This follows Python best practices for exception handling.
1 parent 791deb4 commit 31e6b27

1 file changed

Lines changed: 6 additions & 4 deletions

File tree

maths/collatz_sequence.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,11 @@ def collatz_sequence(n: int) -> Generator[int]:
2323
>>> tuple(collatz_sequence(2.1))
2424
Traceback (most recent call last):
2525
...
26-
Exception: Sequence only defined for positive integers
26+
TypeError: Sequence only defined for integers
2727
>>> tuple(collatz_sequence(0))
2828
Traceback (most recent call last):
2929
...
30-
Exception: Sequence only defined for positive integers
30+
ValueError: Sequence only defined for positive integers
3131
>>> tuple(collatz_sequence(4))
3232
(4, 2, 1)
3333
>>> tuple(collatz_sequence(11))
@@ -44,8 +44,10 @@ def collatz_sequence(n: int) -> Generator[int]:
4444
(43, 130, 65, 196, 98, 49, 148, 74, 37, 112, 56, 28, 14, 7, 22, 11, 34, 17, 52, 26,
4545
13, 40, 20, 10, 5, 16, 8, 4, 2, 1)
4646
"""
47-
if not isinstance(n, int) or n < 1:
48-
raise Exception("Sequence only defined for positive integers")
47+
if not isinstance(n, int):
48+
raise TypeError("Sequence only defined for integers")
49+
if n < 1:
50+
raise ValueError("Sequence only defined for positive integers")
4951

5052
yield n
5153
while n != 1:

0 commit comments

Comments
 (0)