Check Whether the String is Symmetrical or Palindrome - Python
Given a string, the task is to check whether it is symmetrical or a palindrome.
- A string is symmetrical if the first half matches the second half (ignoring the middle character for odd-length strings).
- A string is a palindrome if it reads the same forwards and backwards.
For example:
s = "amaama" -> symmetrical (ama matches ama) and palindrome.
s = "abcba" -> palindrome but not symmetrical (ab ≠ ba).
Let’s explore efficient methods to check symmetry and palindrome properties.
Using String Slicing
This method uses Python’s slicing feature to directly compare parts of the string. It is the fastest and simplest way to check for symmetry and palindrome properties.
s = "abaaba"
half = len(s) // 2
sym = s[:half] == s[half:] if len(s) % 2 == 0 else s[:half] == s[half+1:]
pal = s == s[::-1]
print("Symmetrical" if sym else "Not Symmetrical")
print("Palindrome" if pal else "Not Palindrome")
Output
Symmetrical Palindrome
Explanation:
- s[:half] slices the first half of the string.
- s[half:] or s[half+1:] slices the second half depending on even/odd length.
- s[::-1] reverses the string for the palindrome check.
- Comparisons return True/False and determine the output.
Using Two Pointer Technique
This method uses two pointers from both ends of the string to check palindrome, and a loop to check symmetry by comparing halves. It is memory-efficient and avoids creating extra strings.
s = "amaama"
pal = True
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
pal = False
break
i += 1
j -= 1
half = len(s) // 2
sym = True
for i in range(half):
if len(s) % 2 == 0:
if s[i] != s[i + half]:
sym = False
break
else:
if s[i] != s[i + half + 1]:
sym = False
break
print("Symmetrical" if sym else "Not Symmetrical")
print("Palindrome" if pal else "Not Palindrome")
Output
Symmetrical Palindrome
Explanation:
- Palindrome: while loop compares characters from left (i) and right (j). Breaks on mismatch.
- Symmetry: for loop compares characters of the first half with the second half, skipping the middle character for odd-length strings.
Using all() with Generator Expression
This method uses a generator inside all() to check palindrome. Symmetry is checked by slicing. Efficient because it stops at first mismatch and uses constant extra memory.
s = "amaama"
half = len(s) // 2
# Palindrome
pal = all(s[i] == s[-i-1] for i in range(len(s)//2))
# Symmetry
sym = s[:half] == s[half:] if len(s) % 2 == 0 else s[:half] == s[half+1:]
print("Symmetrical" if sym else "Not Symmetrical")
print("Palindrome" if pal else "Not Palindrome")
Output
Symmetrical Palindrome
Explanation:
- range(len(s)//2) generates indices for the first half.
- s[-i-1] accesses the corresponding character from the end.
- all() returns False at the first mismatch, avoiding unnecessary comparisons.