Problem Statement:
Write a Python function that checks if a given string is a palindrome.
Solution Explanation:
- Convert the string to lowercase using
.lower()
to ensure case insensitivity. - Remove spaces using
.replace(" ", "")
(optional, for handling phrases). - Reverse the string using slicing
[::-1]
. - Compare the original and reversed strings.
Python Code:
def is_palindrome(s): s = s.lower().replace(" ", "") # Convert to lowercase and remove spaces return s == s[::-1] # Compare original with reversed # Test cases print(is_palindrome("madam")) # Output: True print(is_palindrome("racecar")) # Output: True print(is_palindrome("hello")) # Output: False print(is_palindrome("A man a plan a canal Panama")) # Output: True
Example Output:
Input: “madam” → Output: True
Input: “hello” → Output: False
Input: “A man a plan a canal Panama” → Output: True