Skip to content

Commit 2349a4b

Browse files
Enhance palindrome functions with type validation
Refactor palindrome functions to include type checks and remove unnecessary comments.
1 parent ae68a78 commit 2349a4b

File tree

1 file changed

+7
-18
lines changed

1 file changed

+7
-18
lines changed

strings/palindrome.py

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,8 @@
1919

2020

2121
def is_palindrome(s: str) -> bool:
22-
"""
23-
Return True if s is a palindrome otherwise return False.
24-
25-
>>> all(is_palindrome(key) is value for key, value in test_data.items())
26-
True
27-
"""
22+
if not isinstance(s, str):
23+
return False
2824

2925
start_i = 0
3026
end_i = len(s) - 1
@@ -38,23 +34,16 @@ def is_palindrome(s: str) -> bool:
3834

3935

4036
def is_palindrome_traversal(s: str) -> bool:
41-
"""
42-
Return True if s is a palindrome otherwise return False.
37+
if not isinstance(s, str):
38+
return False
39+
if len(s) < 2:
40+
return True
4341

44-
>>> all(is_palindrome_traversal(key) is value for key, value in test_data.items())
45-
True
46-
"""
4742
end = len(s) // 2
4843
n = len(s)
4944

50-
# We need to traverse till half of the length of string
51-
# as we can get access of the i'th last element from
52-
# i'th index.
53-
# eg: [0,1,2,3,4,5] => 4th index can be accessed
54-
# with the help of 1st index (i==n-i-1)
55-
# where n is length of string
56-
return all(s[i] == s[n - i - 1] for i in range(end))
5745

46+
return all(s[i] == s[n - i - 1] for i in range(end))
5847

5948
def is_palindrome_recursive(s: str) -> bool:
6049
"""

0 commit comments

Comments
 (0)