Skip to content

Commit 1ed47ad

Browse files
percy07cclauss
authored andcommitted
Update palindrome.py (#1509)
* Update palindrome.py Add Doctests. * Use test_data to drive the testing
1 parent e3d4d2b commit 1ed47ad

File tree

1 file changed

+49
-14
lines changed

1 file changed

+49
-14
lines changed

other/palindrome.py

+49-14
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,66 @@
1-
# Program to find whether given string is palindrome or not
2-
def is_palindrome(str):
1+
# Algorithms to determine if a string is palindrome
2+
3+
test_data = {
4+
"MALAYALAM": True,
5+
"String": False,
6+
"rotor": True,
7+
"level": True,
8+
"A": True,
9+
"BB": True,
10+
"ABC": False,
11+
"amanaplanacanalpanama": True, # "a man a plan a canal panama"
12+
}
13+
# Ensure our test data is valid
14+
assert all((key == key[::-1]) is value for key, value in test_data.items())
15+
16+
17+
def is_palindrome(s: str) -> bool:
18+
"""
19+
Return True if s is a palindrome otherwise return False.
20+
21+
>>> all(is_palindrome(key) is value for key, value in test_data.items())
22+
True
23+
"""
24+
325
start_i = 0
4-
end_i = len(str) - 1
26+
end_i = len(s) - 1
527
while start_i < end_i:
6-
if str[start_i] == str[end_i]:
28+
if s[start_i] == s[end_i]:
729
start_i += 1
830
end_i -= 1
931
else:
1032
return False
1133
return True
1234

1335

14-
# Recursive method
15-
def recursive_palindrome(str):
16-
if len(str) <= 1:
36+
def is_palindrome_recursive(s: str) -> bool:
37+
"""
38+
Return True if s is a palindrome otherwise return False.
39+
40+
>>> all(is_palindrome_recursive(key) is value for key, value in test_data.items())
41+
True
42+
"""
43+
if len(s) <= 1:
1744
return True
18-
if str[0] == str[len(str) - 1]:
19-
return recursive_palindrome(str[1:-1])
45+
if s[0] == s[len(s) - 1]:
46+
return is_palindrome_recursive(s[1:-1])
2047
else:
2148
return False
2249

2350

24-
def main():
25-
str = "ama"
26-
print(recursive_palindrome(str.lower()))
27-
print(is_palindrome(str.lower()))
51+
def is_palindrome_slice(s: str) -> bool:
52+
"""
53+
Return True if s is a palindrome otherwise return False.
54+
55+
>>> all(is_palindrome_slice(key) is value for key, value in test_data.items())
56+
True
57+
"""
58+
return s == s[::-1]
2859

2960

3061
if __name__ == "__main__":
31-
main()
62+
for key, value in test_data.items():
63+
assert is_palindrome(key) is is_palindrome_recursive(key)
64+
assert is_palindrome(key) is is_palindrome_slice(key)
65+
print(f"{key:21} {value}")
66+
print("a man a plan a canal panama")

0 commit comments

Comments
 (0)