mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-27 15:01:08 +00:00
TypeError for non-integer input (#9250)
* type error check * remove str input * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
parent
7b996e2c22
commit
4f8fa3c44a
|
@ -16,7 +16,15 @@ def num_digits(n: int) -> int:
|
||||||
1
|
1
|
||||||
>>> num_digits(-123456)
|
>>> num_digits(-123456)
|
||||||
6
|
6
|
||||||
|
>>> num_digits('123') # Raises a TypeError for non-integer input
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
TypeError: Input must be an integer
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
if not isinstance(n, int):
|
||||||
|
raise TypeError("Input must be an integer")
|
||||||
|
|
||||||
digits = 0
|
digits = 0
|
||||||
n = abs(n)
|
n = abs(n)
|
||||||
while True:
|
while True:
|
||||||
|
@ -42,7 +50,15 @@ def num_digits_fast(n: int) -> int:
|
||||||
1
|
1
|
||||||
>>> num_digits_fast(-123456)
|
>>> num_digits_fast(-123456)
|
||||||
6
|
6
|
||||||
|
>>> num_digits('123') # Raises a TypeError for non-integer input
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
TypeError: Input must be an integer
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
if not isinstance(n, int):
|
||||||
|
raise TypeError("Input must be an integer")
|
||||||
|
|
||||||
return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1)
|
return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1)
|
||||||
|
|
||||||
|
|
||||||
|
@ -61,7 +77,15 @@ def num_digits_faster(n: int) -> int:
|
||||||
1
|
1
|
||||||
>>> num_digits_faster(-123456)
|
>>> num_digits_faster(-123456)
|
||||||
6
|
6
|
||||||
|
>>> num_digits('123') # Raises a TypeError for non-integer input
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
TypeError: Input must be an integer
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
if not isinstance(n, int):
|
||||||
|
raise TypeError("Input must be an integer")
|
||||||
|
|
||||||
return len(str(abs(n)))
|
return len(str(abs(n)))
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user