6

I have a code to check whether a word is palindrome or not:

str = input("Enter the string")
l = len(str)
p = l-1
index = 0
while index < p:
    if str[index] == str[p]:
        index = index + 1
        p = p-1
        print("String is a palindrome")
        break
    else:
        print("string is not a palindrome")

If a word is inputted, for example : rotor , I want the program to check whether this word is palindrome and give output as "The given word is a palindrome".

But I'm facing problem that, the program checks first r and r and prints "The given word is a palindrome" and then checks o and o and prints "The given word is a palindrome". It prints the result as many times as it is checking the word.

I want the result to be delivered only once. How to change the code?

oguz ismail
  • 1
  • 16
  • 47
  • 69
Kawin M
  • 306
  • 1
  • 2
  • 13
  • Is this an exercise where you have to do it using a `while`, or can you use the simpler, `if word == word[::-1]` ? (where `word` is your input) – Jon Clements Aug 22 '17 at 18:25
  • 1
    Possible duplicate of [How to check for palindrome using Python logic](https://stackoverflow.com/questions/17331290/how-to-check-for-palindrome-using-python-logic) –  Aug 22 '17 at 18:29

9 Answers9

7

Just reverse the string and compare it against the original

string_to_check = input("Enter a string")

if string_to_check == string_to_check[::-1]:
    print("This is a palindrome")
else:
    print("This is not a palindrome")
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
2

I had to make a few changes in your code to replicate the output you said you saw.

Ultimately, what you want is that the message be displayed only at the end of all the comparisons. In your case, you had it inside the loop, so each time the loop ran and it hit the if condition, the status message was printed. Instead, I have changed it so that it only prints when the two pointers index and p are at the middle of the word.

str = input("Enter the string: ")
l = len(str)
p = l-1
index = 0
while index < p:
    if str[index] == str[p]:
        index = index + 1
        p = p-1
        if index == p or index + 1 == p:
            print("String is a palindrome")
    else:
        print("string is not a palindrome")
        break
Antimony
  • 2,230
  • 3
  • 28
  • 38
  • Thanks bro. But I have one doubt, why did used - "index + 1 == p" but not "index == p" in if index == p or index + 1 == p: – Kawin M Aug 22 '17 at 18:47
  • 2
    There can be 2 types of palindromes. Something like "rotor", which has an odd number of letters, and so `index` and `p` would converge on the middle letter. But with other words like "maam", `index` and `p` would end up on the two 'a's in the middle. Hence, to find that end point, we use `index + 1 == p`. – Antimony Aug 22 '17 at 18:50
  • [This](https://stackoverflow.com/questions/3800846/differences-between-input-and-raw-input) is why you should use `raw_input` instead of `input`. – Antimony Aug 22 '17 at 18:54
  • 1
    But raw_input is removed and it is same as input in python 3 right? – Kawin M Aug 22 '17 at 18:56
  • 1
    Oh haha, sorry, didn't notice that you used Python 3. I'll edit the code. – Antimony Aug 22 '17 at 18:57
1

I see that most of the solutions in the internet is where either the string is taken as an input or the string is just reversed and then tested. Below is a solution that considers two points: 1) The input is a very large string therefore, it cannot be just taken from a user. 2) The input string will have capital casing and special characters. 3) I have not looked into the complexity and see further improvement. Would invite suggestions.

    def isPalimdromeStr(self, strInput):
        strLen = len(strInput)
        endCounter = strLen - 1
        startCounter = 0
        while True:
#             print(startCounter, endCounter)
#             print(strInput[startCounter].lower(), strInput[endCounter].lower())

            while not blnValidCh(self, strInput[startCounter].lower()):
                startCounter = startCounter + 1

            while not blnValidCh(self, strInput[endCounter].lower()): 
                endCounter = endCounter - 1

#             print(startCounter, endCounter)
#             print(strInput[startCounter].lower() , strInput[endCounter].lower())
            if (strInput[startCounter].lower() != strInput[endCounter].lower()):
                return False
            else:
                startCounter = startCounter + 1
                endCounter = endCounter - 1

            if (startCounter == strLen - 1):
                return True

#             print("---")


    def blnValidCh(self, ch):
        if rePattern.match(ch):
            return True

        return False

global rePattern
rePattern = re.compile('[a-z]')

blnValidPalindrome = classInstance.isPalimdromeStr("Ma##!laYal!! #am")
print("***")
print(blnValidPalindrome)  
zorze
  • 198
  • 1
  • 6
0
[::-1]

This code is the easiest way of reversing a string. A palindrome is something that reads the same regardless of what side you're reading it from. So the easiest function to check whether or not the word/string is recursive or not would be:

def checkPalindrome(s):
    r = s[::-1]
    if s == r:
        return True
    else:
        return False

Now you can check this code. Eg:

checkPalindrome("madam")
>>> True
checkPalindrome("sentence")
>>> False
0

Change your implementation to the following one:

string_to_be_checked = input("enter your string ")
if string_to_be_checked == string_to_be_checked[::-1] :
    print("palindrome")
else:
    print("not palindrome")
Mark
  • 5,994
  • 5
  • 42
  • 55
0

the easiest way is

str = input('Enter the string: ')

if str == str[::-1]:
   print('Palindrome')
else
   print('Not')

the same login can also be applied to number palindrome

0
def palindrome(s):
    if len(s)<1:
       return True
    else:
        if s[0]==s[-1]:
           return palindrome(s[1:-1])
        else:
           return False
a=str(input("enter data")
if palindrome(a) is True:
    print("string is palindrome")
else:
    print("string is not palindrome")
Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40
maria
  • 1
0
string = 'ASDBDSA'
if string[:]==string[::-1]:
     print("palindrome")
else:
     print("not palindrome")
RAHUL KUMAR
  • 1,123
  • 11
  • 9
0

You can also do it by using ternary operators in python.

string = "Madam"
print("palindrome") if string == string[::-1] else print("not a palindrome")
M.Hassan Nasir
  • 851
  • 2
  • 13