|
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 | + |
3 | 25 | start_i = 0
|
4 |
| - end_i = len(str) - 1 |
| 26 | + end_i = len(s) - 1 |
5 | 27 | while start_i < end_i:
|
6 |
| - if str[start_i] == str[end_i]: |
| 28 | + if s[start_i] == s[end_i]: |
7 | 29 | start_i += 1
|
8 | 30 | end_i -= 1
|
9 | 31 | else:
|
10 | 32 | return False
|
11 | 33 | return True
|
12 | 34 |
|
13 | 35 |
|
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: |
17 | 44 | 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]) |
20 | 47 | else:
|
21 | 48 | return False
|
22 | 49 |
|
23 | 50 |
|
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] |
28 | 59 |
|
29 | 60 |
|
30 | 61 | 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