Python program to check whether the string is Symmetrical
In this tutorial, we will learn to check if a string is symmetrical or not in Python. Strings in Python are a sequence of characters. A string is said to be symmetrical if both the halves of the string are the same. That is the string when broken into two halves from the middle produces two similar sequences of characters.
For example- yoyo is a symmetrical string, when broken from the middle we will get 'yo' and 'yo' which is the same sequence of characters and so the string is symmetrical. for example
Input: madam
Output: No
Input: yoyo
Output: Yes
The simple approach is to break the string into two halves and run a loop to check all the characters in strings of both the halves.
If the characters are not similar then the loops break and the string is not symmetrical otherwise the string is symmetrical. We will define a function that will check for symmetry in the string. First, we have to break the string into two halves from the middle.
The middle index of a string with even digits is calculated as half of the string length. For a string with an odd length, the middle index is half of the length of the string plus 1.
Algorithm
Follow the algorithm to understand the approach better.
Step 1- Define a function that will accept a string and check if it is symmetrical
Step 2- In the function, assign the length of a string to a variable
Step 3- Find the middle index of the string
Step 4- Define start and end values as 0 and mid
Step 5- Run a loop from start to end and check characters for similarity
Step 6- Use a variable to break out of the loop in case of any mismatch
Step 7- If the value in the variable is 0 then print that the string is symmetrical
Python Program
In our program, we used a while loop to check the characters in strings. To break out of the loop in case of any mismatch, we have used a flag variable that will keep track of any different characters is encountered. Initialize flag with 0 in the starting.
def check_sym(string):
n=len(string)
flag=0
if n%2:
mid=n//2+1
else:
mid= n//2
start=0
end= mid
while(start <mid and end<n):
if(string[start]== string[end]):
start= start+1
end= end+1
else:
flag=1
break
if flag==0:
print("symmetrical")
else:
print("not symmetrical")
# main
s= "abcabc"
print (s)
check_sym(s)
s2= "abcdab"
print(s2)
check_sym(s2)
abcabc
symmetrical
abcdab
not symmetrical
Conclusion
In this tutorial, we have discussed how to check if a string is symmetrical or not. First, we have seen what symmetrical string is, then we have discussed the approach we should use for checking if a string is symmetrical or not. The python code for this problem is also given above.