Can we say that a word with 2 characters are palindrome? like "oo" is palindrome and "go" is not?
I am going through a program which is detecting a palindrome from GeeksForGeeks, but it detects go
as palindrome as well, though it is not:
# Function to check whether the # string is plaindrome or not def palindrome(a): # finding the mid, start # and last index of the string mid = (len(a)-1)//2 start = 0 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") # ... other code ... # Driver code string = 'amaama' palindrome(string)
Is there any particular length or condition defined for a word to be a palindrome? I read the Wikipedia article, but did not find any particular condition on the length of a palindrome.
The above program detects "go" as palindrome because the midpoint is 0, which is "g" and the starting point is 0, which is also "g", and so it determines it is a palindrome. But I am still confused about the number of characters. Can a 2 number word be a palindrome? If yes, then do we need to just add a specific condition for it: if word[0] == word[1]
?
Let's take a look at the definition of palindrome, according to Merriam-Webster:
a word, verse, or sentence (such as "Able was I ere I saw Elba") or a number (such as 1881) that reads the same backward or forward
Therefore, two-character words (or any even-numbered character words) can also be palindromes. The example code is simply poorly written and does not work correctly in the case of two-character strings. As you have correctly deduced, it sets the mid
variable to 0
if the length of the string is 2. The loop, while (start < mid)
, is then instantly skipped, as start
is also initialised as 0. Therefore, the flag
variable (initialised as 0
, corresponding to 'is a palindrome') is never changed, so the function incorrectly prints that go
is a palindrome.
There are a number of ways in which you can adapt the algorithm; the simplest of which would be to simply check up to and including the middle character index, by changing the while
condition to start <= mid
. Note that this is only the simplest way to adapt the given code, the simplest piece of Python code to check whether a string is palindromic is significantly simpler (as you can easily reverse a string using a[::-1]
, and compare this to the original string).
(Edit to add: the other answer by trincot actually shows that the provided algorithm is incorrect for all even-numbered character words. The fix suggested in this answer still works.)