Open In App

Python program to check whether the string is Symmetrical or Palindrome

Last Updated : 11 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

Approach 1: The approach is very naive. In the case of palindrome, a loop is run to the mid of the string and the first and last characters are matched. If the characters are not similar then the loop breaks and the string is not palindrome otherwise the string is a palindrome. In the case of symmetry, if the string length is even then the string is broken into two halves and the loop is run, checking the characters of the strings of both the half. If the characters are not similar then the loops break and the string is not symmetrical otherwise the string is symmetrical. If the string length is odd then the string is broken into two halves in such a way that the middle element is left unchecked, and the above same step is repeated.

Below is the implementation.

Python
# Python program to demonstrate
# symmetry and palindrome of the
# string


# Function to check whether the
# string is palindrome or not
def palindrome(a):

    # finding the mid, start
    # and last index of the string
    mid = (len(a)-1)//2  # you can remove the -1 or you add <= sign in line 21
    start = 0  # so that you can compare the middle elements also.
    last = len(a)-1
    flag = 0

    # A loop till the mid of the
    # string
    while(start <= mid):

        # comparing letters from right
        # from the letters from left
        if (a[start] == a[last]):

            start += 1
            last -= 1

        else:
            flag = 1
            break

    # Checking the flag variable to
    # check if the string is palindrome
    # or not
    if flag == 0:
        print("The entered string is palindrome")
    else:
        print("The entered string is not palindrome")

# Function to check whether the
# string is symmetrical or not


def symmetry(a):

    n = len(a)
    flag = 0

    # Check if the string's length
    # is odd or even
    if n % 2:
        mid = n//2 + 1
    else:
        mid = n//2

    start1 = 0
    start2 = mid

    while(start1 < mid and start2 < n):

        if (a[start1] == a[start2]):
            start1 = start1 + 1
            start2 = start2 + 1
        else:
            flag = 1
            break

    # Checking the flag variable to
    # check if the string is symmetrical
    # or not
    if flag == 0:
        print("The entered string is symmetrical")
    else:
        print("The entered string is not symmetrical")


# Driver code
string = 'amaama'
palindrome(string)
symmetry(string)

Output
The entered string is palindrome
The entered string is symmetrical

Time Complexity: O(n)
Auxiliary Space: O(n), where n is number of characters in string.

Approach 2:

We use slicing in this method.

Python
string = 'madam'

length = len(string)
half = length // 2

first_str = string[:half]
second_str = string[half + length % 2:]

# symmetric
if first_str == second_str:
    print(string, 'string is symmetrical')
else:
    print(string, 'string is not symmetrical')

# palindrome
if first_str == second_str[::-1]:  # ''.join(reversed(second_str)) [slower]
    print(string, 'string is palindrome')
else:
    print(string, 'string is not palindrome')

Output
amaama string is symmetrical
amaama string is palindrome

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)
Auxiliary Space: O(n)

METHOD 3:Using re module

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.

Python
# Python program to check whether the string is Symmetrical or Palindrome

import re

input_str = "amaama"
reversed_str = input_str[::-1]

if input_str == reversed_str:
    print("The entered string is symmetrical")
else:
    print("The entered string is not symmetrical")

if re.match("^(\w+)\Z", input_str) and input_str == input_str[::-1]:
    print("The entered string is palindrome")
else:
    print("The entered string is not palindrome")

Output
The entered string is symmetrical
The entered string is palindrome

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.

APPROACH 4:

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.

Python
string = "malayalam"
print("the string is palindrome" if string == ''.join(
    reversed(string)) else "the string is not palindrome")

 Output:

the string is palindrome

Time complexity: O(n)
Space complexity: O(n)



Previous Article
Next Article

Similar Reads

Python program to check whether number formed by combining all elements of the array is palindrome
Given an array arr[], the task is to combine all the elements in the array sequentially and check if it is a palindrome. Examples: Input: arr[] ={1 , 69 , 54 , 45 , 96 , 1} Output: palindrome Explanation: The number formed by combining all the elements is "1695445961" which is a palindrome Input: arr[] ={2 , 73 , 95 , 59 , 96 , 2} Output: not palin
4 min read
Python Program to Check if a String is Palindrome or Not
Given a string, write a python function to check if it is palindrome or not. A string is said to be a palindrome if the reverse of the string is the same as the string. For example, &#x201c;radar&#x201d; is a palindrome, but &#x201c;radix&#x201d; is not a palindrome. Examples: Input : malayalamOutput : YesInput : geeksOutput : NoPython Program to C
4 min read
Python program to check if given string is vowel Palindrome
Given a string (may contain both vowel and consonant letters), remove all consonants, then check if the resulting string is palindrome or not. Examples: Input : abcuhuvmnba Output : YES Explanation : The consonants in the string "abcuhuvmnba" are removed. Now the string becomes "auua". Input : xayzuezyax Output : NO Input : bkldhgcj Output : -1 App
5 min read
Python Program To Check String Is Palindrome Using Stack
A palindrome is a sequence of characters that reads the same backward as forward. Checking whether a given string is a palindrome is a common programming task. In this article, we will explore how to implement a Python program to check if a string is a palindrome using a stack. Example Input: str = “geeksforgeeks” Output: NoInput: str = “madam” Out
3 min read
Python Program to check whether all elements in a string list are numeric
Given a list that contains only string elements the task here is to write a Python program to check if all of them are numeric or not. If all are numeric return True otherwise, return False. Input : test_list = ["434", "823", "98", "74"] Output : True Explanation : All Strings are digits.Input : test_list = ["434", "82e", "98", "74"] Output : False
5 min read
Python Program to check whether Characters of all string elements are in lexical order or not
Given a list with string elements, the task is to write a Python program to return True if all list elements are sorted. The point of caution here is to keep in mind we are comparing characters of a string list element with other characters of the same list element and not string elements with each other. Examples: Input : test_list = ["dent", "flo
4 min read
Python program to check if number is palindrome (one-liner)
In this article, we are given a number and we have to check whether the number is palindrome or not in one-liner code. The output will be True if it's a Palindrome number otherwise it would be False. Let's discuss how to find whether a number is palindrome or not in this article. Input1: test_number = 12321 Output1: True Input2: test_number = 1234
3 min read
Python Program To Check If A Singly Linked List Is Palindrome
Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. METHOD 1 (Use a Stack): A simple solution is to use a stack of list nodes. This mainly involves three steps.Traverse the given list from head
6 min read
Python Program To Check If A Linked List Of Strings Forms A Palindrome
Given a linked list handling string data, check to see whether data is palindrome or not? Examples: Input: a -&gt; bc -&gt; d -&gt; dcb -&gt; a -&gt; NULL Output: True String "abcddcba" is palindrome. Input: a -&gt; bc -&gt; d -&gt; ba -&gt; NULL Output: False String "abcdba" is not palindrome. Recommended: Please solve it on "PRACTICE" first, befo
2 min read
Python Set | Check whether a given string is Heterogram or not
Given a string S of lowercase characters. The task is to check whether a given string is a Heterogram or not using Python. A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once. Input1: S = "the big dwarf only jumps"Output1: YesExplanation: Each alphabet in the string S is occurred only once.Input2: S
3 min read