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
defis_palindrome(s):
returnall(s[i] == s[-(i + 1)] for i inrange(len(s)//2))
defnormalized_palindrome(s):
return is_palindrome("".join(c for c in s.replace(" ","").lower() if c notin punctuation))
You can also use zip
and reversed
to iterate pairwise over letters:
defis_palindrome(s):
returnall(a == b for a, b inzip(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()>>>defispalindrome(word):...iflen(word) < 2: returnTrue...if word[0] != word[-1]: returnFalse...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.
defisPalindrome(s: str) -> bool:
mystring = s.lower()
mystring2 = ""for i inmystring:if i.isalnum():
mystring2 += i
return (mystring2 == mystring2[::-1])
Post a Comment for "Need To Derive A Function For Palindrome"