diff --git a/strings/palindrome.py b/strings/palindrome.py index 4df5639b0c49..7a513942c43d 100644 --- a/strings/palindrome.py +++ b/strings/palindrome.py @@ -24,8 +24,15 @@ def is_palindrome(s: str) -> bool: >>> all(is_palindrome(key) == value for key, value in test_data.items()) True + >>> is_palindrome(123) + Traceback (most recent call last): + ... + TypeError: Input must be a string """ + if not isinstance(s, str): + raise TypeError("Input must be a string") + start_i = 0 end_i = len(s) - 1 while start_i < end_i: @@ -44,6 +51,9 @@ def is_palindrome_traversal(s: str) -> bool: >>> all(is_palindrome_traversal(key) == value for key, value in test_data.items()) True """ + if not isinstance(s, str): + raise TypeError("Input must be a string") + end = len(s) // 2 n = len(s) @@ -63,6 +73,9 @@ def is_palindrome_recursive(s: str) -> bool: >>> all(is_palindrome_recursive(key) == value for key, value in test_data.items()) True """ + if not isinstance(s, str): + raise TypeError("Input must be a string") + if len(s) <= 1: return True if s[0] == s[len(s) - 1]: @@ -78,6 +91,9 @@ def is_palindrome_slice(s: str) -> bool: >>> all(is_palindrome_slice(key) == value for key, value in test_data.items()) True """ + if not isinstance(s, str): + raise TypeError("Input must be a string") + return s == s[::-1] diff --git a/strings/reverse_letters.py b/strings/reverse_letters.py index cd1b7832d066..770796f8110e 100644 --- a/strings/reverse_letters.py +++ b/strings/reverse_letters.py @@ -12,6 +12,12 @@ def reverse_letters(sentence: str, length: int = 0) -> str: >>> reverse_letters("racecar") 'racecar' """ + if not isinstance(sentence, str): + raise TypeError("sentence must be a string") + + if not isinstance(length, int) or length < 0: + raise ValueError("length must be a non-negative integer") + return " ".join( word[::-1] if len(word) > length else word for word in sentence.split() )