Skip to content

Commit aa8379b

Browse files
committed
type error check
1 parent eaa87bd commit aa8379b

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

maths/number_of_digits.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,15 @@ def num_digits(n: int) -> int:
1616
1
1717
>>> num_digits(-123456)
1818
6
19+
>>> num_digits('123') # Raises a TypeError for non-integer input
20+
Traceback (most recent call last):
21+
...
22+
TypeError: Input must be an integer
1923
"""
24+
25+
if not isinstance(n, int):
26+
raise TypeError("Input must be an integer")
27+
2028
digits = 0
2129
n = abs(n)
2230
while True:
@@ -42,7 +50,15 @@ def num_digits_fast(n: int) -> int:
4250
1
4351
>>> num_digits_fast(-123456)
4452
6
53+
>>> num_digits('123') # Raises a TypeError for non-integer input
54+
Traceback (most recent call last):
55+
...
56+
TypeError: Input must be an integer
4557
"""
58+
59+
if not isinstance(n, int):
60+
raise TypeError("Input must be an integer")
61+
4662
return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1)
4763

4864

@@ -61,7 +77,15 @@ def num_digits_faster(n: int) -> int:
6177
1
6278
>>> num_digits_faster(-123456)
6379
6
80+
>>> num_digits('123') # Raises a TypeError for non-integer input
81+
Traceback (most recent call last):
82+
...
83+
TypeError: Input must be an integer
6484
"""
85+
86+
if not isinstance(n, int):
87+
raise TypeError("Input must be an integer")
88+
6589
return len(str(abs(n)))
6690

6791

@@ -76,7 +100,7 @@ def benchmark_a_function(func: Callable, value: int) -> None:
76100
timing = timeit(f"__main__.{call}", setup="import __main__")
77101
print(f"{call}: {func(value)} -- {timing} seconds")
78102

79-
for value in (262144, 1125899906842624, 1267650600228229401496703205376):
103+
for value in ('262144', 1125899906842624, 1267650600228229401496703205376):
80104
for func in (num_digits, num_digits_fast, num_digits_faster):
81105
benchmark_a_function(func, value)
82106
print()

0 commit comments

Comments
 (0)