From baaf7f047d782b7ba5dd0e776650a327e8783ce9 Mon Sep 17 00:00:00 2001 From: Joao Pedro Campos Silva Date: Tue, 8 Oct 2024 22:50:20 +0200 Subject: [PATCH] Refactor palindrome checker functions - Updated the function is_palindrome_recursive to handle strings of length 1 or less. - Simplified the logic in the function is_palindrome_reverse by using string slicing. - Optimized the function is_palindrome_iterative by removing unnecessary lines of code. --- .../src/palindrome_checker/palindrome.py | 39 +++++++++++-------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/code/string_algorithms/src/palindrome_checker/palindrome.py b/code/string_algorithms/src/palindrome_checker/palindrome.py index 12cb6abd4f..641ab610d4 100644 --- a/code/string_algorithms/src/palindrome_checker/palindrome.py +++ b/code/string_algorithms/src/palindrome_checker/palindrome.py @@ -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