Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Python palindrome checker functions #6798

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 22 additions & 17 deletions code/string_algorithms/src/palindrome_checker/palindrome.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,40 @@
def isPalindromeRecursive(string):
if len(string) == 2 or len(string) == 1:
def is_palindrome_recursive(string):
if len(string) <= 1:
return True
if string[0] != string[len(string) - 1]:

if string[0] != string[-1]:
return False
return isPalindromeRecursive(string[1 : len(string) - 1])

return is_palindrome_recursive(string[1:-1])


def isPalindromeReverse(string):
def is_palindrome_reverse(string):
return string == string[::-1]


def isPalindromeIterative(string):
def is_palindrome_iterative(string):
start = 0
end = len(string) - 1

while start < end:
start = start + 1
end = end - 1
if string[start] != string[end]:
return False

start += 1
end -= 1

return True


if __name__ == "__main__":
print(isPalindromeRecursive("alpha")) # should output false
print(isPalindromeRecursive("racecar")) # should output true
print(isPalindromeRecursive("abba")) # should output true
print(is_palindrome_recursive("alpha")) # should output false
print(is_palindrome_recursive("racecar")) # should output true
print(is_palindrome_recursive("abba")) # should output true

print(isPalindromeReverse("alpha")) # should output false
print(isPalindromeReverse("racecar")) # should output true
print(isPalindromeReverse("abba")) # should output true
print(is_palindrome_reverse("alpha")) # should output false
print(is_palindrome_reverse("racecar")) # should output true
print(is_palindrome_reverse("abba")) # should output true

print(isPalindromeIterative("alpha")) # should output false
print(isPalindromeIterative("racecar")) # should output true
print(isPalindromeIterative("abba")) # should output true
print(is_palindrome_iterative("alpha")) # should output false
print(is_palindrome_iterative("racecar")) # should output true
print(is_palindrome_iterative("abba")) # should output true