From 3338bee2f4e640bc4784aba2fcf173ad900d45e1 Mon Sep 17 00:00:00 2001 From: Lily Sam <41793292+oforiwaasam@users.noreply.github.com> Date: Wed, 3 May 2023 22:19:38 -0400 Subject: [PATCH] add recursive palindrome checker --- algorithms/Python/README.md | 1 + .../Python/recursion/recursive_palindrome.py | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 algorithms/Python/recursion/recursive_palindrome.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 56e61288..59dfcf0f 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -29,6 +29,7 @@ - [Recursive Insertion Sort](recursion/recursive_insertion_sort.py) - [Recursive Sum of n numbers](recursion/recursive-sum-of-n-numbers.py) - [GCD by Euclid's Algorithm](recursion/gcd_using_recursion.py) +- [Recursive Is-Palindrome](recursion/recursive_palindrome.py) ## Scheduling diff --git a/algorithms/Python/recursion/recursive_palindrome.py b/algorithms/Python/recursion/recursive_palindrome.py new file mode 100644 index 00000000..39b83e9d --- /dev/null +++ b/algorithms/Python/recursion/recursive_palindrome.py @@ -0,0 +1,20 @@ +""" +Function that uses a recursive approach to check +if a string is a palindrome +Time Complexity: O(N) where N is the length of the +string +""" + +def recursive_is_palindrome(s: str) -> bool: + if len(s) <= 1: + return True + if s[0] != s[-1]: + return False + return recursive_is_palindrome(s[1:-1]) + + +# test cases +print(recursive_is_palindrome("abba") is True) +print(recursive_is_palindrome("abba") is True) +print(recursive_is_palindrome("") is True) +print(recursive_is_palindrome("abcd") is False) \ No newline at end of file