When it is required to check if a string is symmetrical or it is a palindrome, a method can be defined, that uses the ‘while’ condition. Another method is defined to check the symmetry that uses the ‘while’ and ‘if’ conditions too.
A palindrome is a number or string, which when read from left to right or right to left is the same value. The index values are the same.
Example
Below is a demonstration for the same −
def check_palindrome(my_str): mid_val = (len(my_str)-1)//2 start = 0 end = len(my_str)-1 flag = 0 while(start<mid_val): if (my_str[start]== my_str[end]): start += 1 end -= 1 else: flag = 1 break; if flag == 0: print("The entered string is palindrome") else: print("The entered string is not palindrome") def check_symmetry(my_str): n = len(my_str) flag = 0 if n%2: mid_val = n//2 +1 else: mid_val = n//2 start_1 = 0 start_2 = mid_val while(start_1 < mid_val and start_2 < n): if (my_str[start_1]== my_str[start_2]): start_1 = start_1 + 1 start_2 = start_2 + 1 else: flag = 1 break if flag == 0: print("The entered string is symmetrical") else: print("The entered string is not symmetrical") my_string = 'phphhphp' print("The method to check a palindrome is being called...") check_palindrome(my_string) print("The method to check symmetry is being called...") check_symmetry(my_string)
Output
The method to check a palindrome is being called... The entered string is palindrome The method to check symmetry is being called... The entered string is not symmetrical
Explanation
- A method named ‘check_palindrome‘ is defined, that takes a string as a parameter.
- The middle value is calculated by doing floor division with 2.
- The start value is assigned to 0, and end value is assigned to the last element.
- A variable named flag is assigned to 0.
- A while condition begins, and if the start and end elements are equal, the start value is incremented, and end value is decremented.
- Otherwise, the flag variable is assigned to 1, and it breaks out of the loop.
- If the value of flag is 0, the string would be a palindrome, otherwise not.
- Another method named ‘check_symmetry’ is defined, that takes a string as a parameter.
- The length of the string is assigned to a variable.
- If the remainder of the length and 2 is not 0, the middle value is changed.
- The start and middle value are changed again.
- Another ‘while’ condition is used, and the start values are changed again.
- If the value of flag is 0, then the string is considered symmetrical.
- Otherwise not.