Python program to check whether the string is Symmetrical or Palindrome
Last Updated :
23 Dec, 2024
Given a string. the task is to check if the string is symmetrical and palindrome or not. A string is said to be symmetrical if both the halves of the string are the same and a string is said to be a palindrome string if one half of the string is the reverse of the other half or if a string appears the same when read forward or backward.
Example:
Input: khokho
Output:
The entered string is symmetrical
The entered string is not palindrome
Input:amaama
Output:
The entered string is symmetrical
The entered string is palindrome
Naive Approach
For checking if a string is a palindrome, we can use a loop to compare characters from the start and end moving towards the middle. For checking symmetry, we split the string into two halves and compare them.
Below is the implementation.
Python
def palindrome(s):
return s == s[::-1]
def is_symmetrical(s):
length = len(s)
mid = length // 2
if length % 2 == 0:
return s[:mid] == s[mid:]
else:
return s[:mid] == s[mid+1:]
s = "amaama"
if symmetrical(s):
print("Symmetrical")
else:
print("Not Symmetrical")
if palindrome(s):
print("Palindrome")
else:
print("Not Palindrome")
Output:
The entered string is symmetrical
The entered string is palindrome
Time Complexity: O(n)
Auxiliary Space: O(n), where n is number of characters in string.
Using Slicing
We use slicing to reverse the string for palindrome checking and split the string for symmetry checking.
Example:
Python
s = 'amaama'
half = len(s) // 2
s1 = s[:half]
s2 = s[half:] if len(s) % 2 == 0 else s[half + 1:]
if s1 == s2:
print(f"{s} is symmetrical")
else:
print(f"{s} is not symmetrical")
Outputamaama is symmetrical
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Using Regular Expressions
Approach:
In the above code, we first check if the string is symmetrical or not using slicing. Then, we use the re.match function to match the pattern of the string with a regular expression that matches one or more word characters and ensures that the string ends there. Finally, we check if the original string is equal to its reversed version to determine if it’s a palindrome or not.
Algorithm:
1. Define a string input_str to be checked for symmetry and palindrome
2. Reverse the input_str using string slicing and store it in reversed_str
3. Check if the input_str and reversed_str are equal to each other. If yes, then the input_str is symmetrical
4. Use a loop to iterate through the input_str and compare the characters with the corresponding characters in the reversed_str. If any character does not match, then the string is not symmetrical
5. Use recursion to check if the string is symmetrical. If the length of the string is less than 2 or the first and last characters of the string are not the same, then return False. Otherwise, call the function recursively with the substring obtained by removing the first and last characters of the original string
6. Use built-in functions and regular expressions to check if the input_str is palindrome or not. The re.match function is used to match the pattern of the string with a regular expression that matches one or more word characters and ensures that the string ends there.
Example:
Python
import re
def palindrome(s):
# Remove non-alphanumeric characters and convert to lowercase
s1 = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
# Check if the cleaned string matches its reverse
return s1 == s1[::-1]
def symmetrical(s):
# Remove spaces and check halves
s2 = re.sub(r'\s+', '', s) # Remove spaces
length = len(s2)
mid = length // 2
if length % 2 == 0:
return s2[:mid] == s2[mid:]
else:
return s2[:mid] == s2[mid+1:]
# Test the functions
s = "madam"
print(f"Is '{s}' Palindrome? {palindrome(s)}")
print(f"Is '{s}' Symmetrical? {symmetrical(s)}")
s = "abba"
print(f"Is '{s}' Palindrome? {palindrome(s)}")
print(f"Is '{s}' Symmetrical? {symmetrical(s)}")
OutputIs 'madam' Palindrome? True
Is 'madam' Symmetrical? False
Is 'abba' Palindrome? True
Is 'abba' Symmetrical? False
Time complexity: The time complexity of the program is O(n), where n is the length of the input string. This is because the program performs a single pass over the string to reverse it, and then checks if the reversed string is equal to the original string, and also checks if the original string is a palindrome using regex.
Space complexity: The space complexity of the program is O(n), where n is the length of the input string. This is because the program creates a new string to store the reversed input string, and also uses regex to check for palindrome, which may require additional memory for regex matching.
Using reversed() Function
We can check the strings whether it is palindrome or not by using the reversed() function to the string which reverses the string which makes us easy to write the program.
Example:
Python
def is_palindrome_reversed(s):
# Use reversed() to reverse the string and join it to form a new string
s1 = ''.join(reversed(s))
return s == s1
def symmetrical(s):
# Calculate the midpoint of the string
mid = len(s) // 2
# Split the string into two halves
if len(s) % 2 == 0:
s1 = s[:mid]
s2 = s[mid:]
else:
s1 = s[:mid]
s2 = s[mid + 1:]
return s1 == s2
# Test the functions
str = ["khokho", "amaama", "malayalam"]
for s in str:
print(f"Testing string: {s}")
if symmetrical(s):
print("Symmetrical")
else:
print("Not a Symmetrical")
if is_palindrome_reversed(s):
print("Palindrome")
else:
print("Not a Palindrome")
OutputTesting string: khokho
Symmetrical
Not a Palindrome
Testing string: amaama
Symmetrical
Palindrome
Testing string: malayalam
Not a Symmetrical
Palindrome
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Python program to check whether the string is Symmetrical or Palindrome – FAQs
What is the difference between a symmetrical and a palindrome string?
- Symmetrical String: A string is considered symmetrical if it reads the same forwards and backwards, but the term is often used in a broader context to include any pattern or shape that exhibits symmetry.
- Palindrome String: A string is a palindrome if it reads the same forwards and backwards. This is a specific case of symmetry where the string’s symmetry is with respect to its own center.
In summary, all palindromes are symmetrical, but not all symmetrical strings are palindromes.
How to write a function to check string symmetry in Python?
You can write a function to check if a string is symmetrical by comparing it to its reversed version.
Example:
def is_symmetric(s):
return s == s[::-1]
# Example usage
print(is_symmetric("abba")) # Output: True
print(is_symmetric("abcd")) # Output: False
What built-in methods can help in palindrome checking in Python?
Python provides several built-in methods and techniques that can help check if a string is a palindrome:
1. String Slicing: Use slicing to reverse the string and compare it with the original string.
def is_palindrome(s):
return s == s[::-1]
2. 'str[::-1]': This slicing method reverses the string and can be used in comparison.
s = "madam"
if s == s[::-1]:
print("Palindrome")
3. 'str.join()': For more complex palindrome checks involving separators or spaces.
def is_palindrome_with_spaces(s):
cleaned = ''.join(s.split())
return cleaned == cleaned[::-1]
How to optimize palindrome checking for large strings in Python?
To optimize palindrome checking for large strings, consider the following techniques:
1. Early Termination: Check characters from both ends towards the center. This allows you to terminate early if a mismatch is found.
def is_palindrome_optimized(s):
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
2. Avoid Reversal: Instead of creating a reversed copy of the string, compare characters from the ends as shown above.
3. Ignoring Case and Non-Alphanumeric Characters: Clean the string by removing non-alphanumeric characters and converting it to lower case before checking.
def is_palindrome_cleaned(s):
cleaned = ''.join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]
4. Memory Efficiency: For very large strings, consider using generators or iterators to process chunks of the string if applicable.