Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Simple function to check whether a word is palindrome or not

I’m still new to python. It’ll be really helpful if someone can point out what’s wrong in the code here.

def palindrome(s):
    for i in range(0, len(s)):
        x = (s[i] == s[-1-i])
        if x == True:
            return x
        else:
            x = False
            return x
            break
def palindrome(s):
    for i in range(0, len(s)):
        x = (s[i] == s[-1-i])
        if x == True:
            return x
        else:
            return x
            break
palindrome('loll')

Using this function returns True instead of False.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re always returning on the first iteration of your loop. This means the loop only executes once. If the first and last letter are equal it will determine you have a palindrome.

But you can only short-circuit on finding a mis-match, so you should only return early in this situation.

def palindrome(s):
    for i in range(0, len(s)):
        x = (s[i] == s[-1-i])
        if not x:
            return False
    return True

But you really only need to iterate halfway, and assigning to x is unnecessary.

def palindrome(s):
    for i in range(0, len(s) // 2):
        if s[i] != s[-1-i]:
            return False
    return True

To further refine this, all implements this kind of short-circuiting, and we can feed it a generator expression.

def palindrome(s):
    return all(
        s[i] == s[-1 - i]
        for i in range(len(s) // 2)
    )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading