Skip to content

Commit f6e7db6

Browse files
Add input validation to palindrome functions
1 parent 5d93c44 commit f6e7db6

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

strings/palindrome.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,15 @@ def is_palindrome(s: str) -> bool:
2424
2525
>>> all(is_palindrome(key) == value for key, value in test_data.items())
2626
True
27+
>>> is_palindrome(123)
28+
Traceback (most recent call last):
29+
...
30+
TypeError: Input must be a string
2731
"""
2832

33+
if not isinstance(s, str):
34+
raise TypeError("Input must be a string")
35+
2936
start_i = 0
3037
end_i = len(s) - 1
3138
while start_i < end_i:
@@ -44,6 +51,9 @@ def is_palindrome_traversal(s: str) -> bool:
4451
>>> all(is_palindrome_traversal(key) == value for key, value in test_data.items())
4552
True
4653
"""
54+
if not isinstance(s, str):
55+
raise TypeError("Input must be a string")
56+
4757
end = len(s) // 2
4858
n = len(s)
4959

@@ -63,6 +73,9 @@ def is_palindrome_recursive(s: str) -> bool:
6373
>>> all(is_palindrome_recursive(key) == value for key, value in test_data.items())
6474
True
6575
"""
76+
if not isinstance(s, str):
77+
raise TypeError("Input must be a string")
78+
6679
if len(s) <= 1:
6780
return True
6881
if s[0] == s[len(s) - 1]:
@@ -78,6 +91,9 @@ def is_palindrome_slice(s: str) -> bool:
7891
>>> all(is_palindrome_slice(key) == value for key, value in test_data.items())
7992
True
8093
"""
94+
if not isinstance(s, str):
95+
raise TypeError("Input must be a string")
96+
8197
return s == s[::-1]
8298

8399

0 commit comments

Comments
 (0)