def isPalindrome(string):
#termination condition: the string is one character or less
if (len(string) <= 1):
return True
if (string[0] == string[-1]):
return isPalindrome(string[1:-1])
else:
return False
How to check if a given string is a palindrome, in Python?
"""
This implementation checks whether a given
string is a palindrome. A string is
considered to be a palindrome if it reads the
same forward and backward. For example, "kayak"
is a palindrome, while, "door" is not.
Let n be the length of the string
Time complexity: O(n),
Space complexity: O(1)
"""
def isPalindrome(string):
# Maintain left and right pointers
leftIdx = 0
rightIdx = len(string)-1
while leftIdx < rightIdx:
# If chars on either end don't match
# string cannot be a palindrome
if string[leftIdx] != string[rightIdx]:
return False
# Otherwise, proceed to next chars
leftIdx += 1
rightIdx -= 1
return True
print(isPalindrome("kayak")) # True
print(isPalindrome("door")) # False
myString = "aba"
if myString == myString[::-1]:
print("The string '" + myString + "' is a palindrome")
else:
print("The string '" + myString + "' is not a palindrome")
string = input("Type a string: ")
if string[::-1] == string:
print(string,"This string is Palindrome")
else:
print(string,"This string is not Palindrome")
def reverse(n, rev=0):
if n == 0:
return rev
rev = rev * 10 + (n % 10)
rev = reverse(n // 10, rev)
return rev
n = int(input("Enter a no.:"))
if n == reverse(n):
print(n,' is a Palindrome')
else:
print(n,' is not a Palindrome')