Skip to content Skip to sidebar Skip to footer

Need To Derive A Function For Palindrome

I need to derive a function which takes a string and returns whether or not that string is a palindrome and my function should return True on strings which are palindromes if space

Solution 1:

>>> text = 'a man a plan a canal panama'
>>> x = ''.join(text.split())
>>> x == x[::-1]
True

Solution 2:

Outline

A phrase is a palindrome if the i'th character is the same as the len-i'th character. Since the series is a mirror image, you haveto go only as far as the middle.

To get the effect you are looking for,you can normalize on whitespace, punctuation, and string case before calculating whether a string is a palindrome or not..

Code

from string import punctuation

def is_palindrome(s):
    return all(s[i] == s[-(i + 1)] for i in range(len(s)//2))

def normalized_palindrome(s):
    return is_palindrome("".join(c for c in s.replace(" ","").lower() if c not in punctuation))

You can also use zip and reversed to iterate pairwise over letters:

def is_palindrome(s):
    return all(a == b for a, b in zip(s, reversed(s)))

Of course, that does not stop in the middle.

Test

>>> tests = [
...     "able was I ere I saw Elba",
...     "a man, a plan, a canal: Panama!",
...     "Was it Eliot's toilet I saw?",
... ]
>>> 
>>> for test in tests:
...     print normalized_palindrome(test)
... 
True
True
True

Your code

As for your original, it's correct by me:

>>> s = "able was I ere I saw Elba".lower()
>>> def ispalindrome(word):
...     if len(word) < 2: return True
...     if word[0] != word[-1]: return False
...     return ispalindrome(word[1:-1])
... 
>>> ispalindrome(s)
True
>>> s = "a man a plan a canal panama"
>>> ispalindrome(s)
False
>>> ispalindrome(s.replace(" ",""))
True

Solution 3:

You can store the string that is free of special characters and spaces and then check if it is a palindrome or not.

def isPalindrome(s: str) -> bool:
    mystring = s.lower()
    mystring2 = ""
    for i in mystring:
        if i.isalnum():
            mystring2 += i

    return (mystring2 == mystring2[::-1])

Post a Comment for "Need To Derive A Function For Palindrome"