Zain Mohamed
Zain Mohamed

Reputation: 23

How to check is a word is a palindrome of another word

I've created a python program where the user enters a word, then the program turns the word into a list. The user then enters a letter and then the program tell you how many times the letter appears. Now I need to add more program to check it the word that was entered at the beginning is a palindrome. If it is there will be a good message and if not a false message. Not really sure how to start. Any help?

Upvotes: 0

Views: 147

Answers (4)

opeonikute
opeonikute

Reputation: 552

You could use a simple conditional statement. This should be much easier to understand for the beginner. For example:

    text = "Rapport"
    def palindrome(text)
       if text[::-1] == text:
          return True
       else: 
          return False 

I believe this should be pretty easy to understand. text[::-1] is the fastest approach. A much slower approach is using ''.join(reversed(list)), where the list is the list you split your text into. You can verify which approach you want to take by timing your code using timeit.

Although, timing the slicing of your code is considered a bad benchmark so time the whole code. Hope I explained well enough. Good luck!

Edit: your code is good but you need to remember that a function takes in an argument as a value, which is what you manipulate in the function itself.

Your final code should look something like this: text = StrVar()

def getPalindrome(word):
    if word == word[::-1]:
       return True
    else :
       return False

palindrome = getPalindrome(text)

Notice that the function's argument is different from the text itself, which I assigned a string variable to also show that you don't need to give it a value right away. Make your code elegant.

Upvotes: 0

Zain Mohamed
Zain Mohamed

Reputation: 23

Okay so I've looked over all of your answers. Would this code be suitable or even a proper peice of code which isn't utter s**t?

def getPalindrome()
    if word == word[::-1] :
       print(True)
    else :
       print(False)

palindrome = getPalindrome()

Upvotes: 0

Reut Sharabani
Reut Sharabani

Reputation: 31339

There is a known "trick" for that in python, reversing the word using [::-1]. Not the most efficient though:

>>> "racecar" == "racecar"[::-1]
True
>>> "racecars" == "racecars"[::-1]
False

Upvotes: 1

Frerich Raabe
Frerich Raabe

Reputation: 94319

You can reverse the string and check whether it's equal to the input string:

def palindrome(s):
    return s == s[::-1]

Upvotes: 6

Related Questions