f is_palindrome_recursive(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome_recursive(s[1:-1])
string = input("Enter a string: ")
processed_string = string.replace(" ", "").lower()
if is_palindrome_recursive(processed_string):
print(f'"{string}" is a palindrome.')
else:
print(f'"{string}" is not a palindrome.')
#source code --> clcoding.com
Code Explanation:
def is_palindrome_recursive(s):
This line defines a function named is_palindrome_recursive, which will check whether a given string s is a palindrome.
A palindrome is a word, phrase, or sequence that reads the same forward and backward (ignoring spaces and capitalization).
if len(s) <= 1:
return True
This line checks if the length of the string s is less than or equal to 1.
If the string is empty or has only one character, it is trivially a palindrome, so the function returns True.
Example: "a", "b", or an empty string "" are all palindromes.
if s[0] != s[-1]:
return False
This checks if the first character (s[0]) is not equal to the last character (s[-1]).
If the first and last characters are not the same, the string cannot be a palindrome, so it returns False.
return is_palindrome_recursive(s[1:-1])
If the first and last characters are the same, the function makes a recursive call with a substring that excludes the first and last characters (s[1:-1]).
This means the function will continue checking the inner characters of the string, ignoring the outer characters.
The recursion keeps narrowing the string until it either finds a mismatch (and returns False), or the string becomes too short to continue (and returns True).
Input Handling
string = input("Enter a string: ")
This line prompts the user to enter a string. The input is stored in the variable string.
processed_string = string.replace(" ", "").lower()
This line processes the string by removing any spaces with replace(" ", "") and converting all characters to lowercase using lower().
This ensures that the palindrome check is case-insensitive and doesn't consider spaces.
if is_palindrome_recursive(processed_string):
print(f'"{string}" is a palindrome.')
else:
print(f'"{string}" is not a palindrome.')
The if statement calls the is_palindrome_recursive function, passing the processed string (processed_string), which has no spaces and is in lowercase.
If the function returns True, it prints that the original string (string) is a palindrome.
If the function returns False, it prints that the original string is not a palindrome.
0 Comments:
Post a Comment