Palindrome recursive function - python

I tried to write a recursive function that says if a string is a palindrome, but all I get is an infinite loop and I don't know what the problem is
def isPalindrome(S):
listush=list(S) #listush=['a', 'b', 'n', 'n', 'b', 'a']
length=len(listush) #length=6
if length==0 or length==1:
return S, "is a palindrome!"
elif listush[0]!=listush[-1]:
return S, "is not a palindrome!"
else:
del listush[0]
del listush[-1]
return isPalindrome(S)
print isPalindrome("abnnba")

Hope this helps
def ispalindrome(word):
if len(word)<=1:
print("Palindrome")
return
else:
if word[0]!=word[-1]:
print("Not a palindrome")
return
return ispalindrome(word[1:len(word)-1])
word=input("Enter word ")
ispalindrome(word)

First of all, indent your code properly.
Secondly, you are calling the function again with the same argument. Call with 'listush' list from which you are deleting or delete from 'S' and recurse with S argument.

There's no need for creating a list. A python string is already an indexable sequence.
Even better, we can employ slicing and let the function return True and False instead of a tuple with text, With all of this, isPalindrome() becomes a one-liner:
def isPalindrome(S):
return len(S) < 2 or (S[0] == S[-1] and isPalindrome(S[1:-2]))
print isPalindrome('A')
>>> True
print isPalindrome('AA')
>>> True
print isPalindrome('BAAB')
>>> True
print isPalindrome('ABAB')
>>> False

There are some things I would like to say about your code
You can send a slice of the list, saving you the trouble of deleting
elements.
You don't need to convert it to a list, all the operations you need
in finding palindrome are supported by strings.
You are returning S in the recursive function, which would be an
empty list(or string) because it is diminishing each recursion. In
recursive cases, I suggest you to just return True or False
Here is an example.
def isPalindrome(S):
length=len(S)
if length < 2:
return True
elif S[0] != S[-1]:
return False
else:
return isPalindrome(S[1:length - 1])
Simple as that.

If you do an print(listush) you can see, that your list never changes.
The following modification of your code works:
def isPalindrome(testStr, orig=None):
if orig is None:
orig = testStr
length = len(testStr) #length=6
print(testStr)
if length == 0 or length == 1:
return orig, "is a palindrome!"
elif testStr[0] != testStr[-1]:
return orig, "is not a palindrome!"
else:
return isPalindrome(testStr[1:-1], orig)
print isPalindrome("abnnba")

Related

How do make a function that verifies if a piece of string is the mirror of another using a for loop? [duplicate]

I'm trying to check for a palindrome with Python. The code I have is very for-loop intensive.
And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it's just not making the most of the language.
I see on this website. Search for "C-style for", that Python doesn't have C-style for loops. Might be outdated, but I interpret it to mean Python has its own methods for this.
I've tried looking around, I can't find much up to date (Python 3) advice for this. How can I solve a palindrome challenge in Python, without using the for loop?
I've done this in C in class, but I want to do it in Python, on a personal basis. The problem is from the Euler Project, great site By the way,.
def isPalindrome(n):
lst = [int(n) for n in str(n)]
l=len(lst)
if l==0 || l==1:
return True
elif len(lst)%2==0:
for k in range (l)
#####
else:
while (k<=((l-1)/2)):
if (list[]):
#####
for i in range (999, 100, -1):
for j in range (999,100, -1):
if isPalindrome(i*j):
print(i*j)
break
I'm missing a lot of code here. The five hashes are just reminders for myself.
Concrete questions:
In C, I would make a for loop comparing index 0 to index max, and then index 0+1 with max-1, until something something. How to best do this in Python?
My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?
Does anybody have any good advice, or good websites, or resources for people in my position? I'm not a programmer, I don't aspire to be one, I just want to learn enough so that when I write my bachelor's degree thesis (electrical engineering), I don't have to simultaneously LEARN an applicable programming language while trying to obtain good results in the project. "How to go from basic C to great application of Python", that sort of thing.
Any specific bits of code to make a great solution to this problem would also be appreciated, I need to learn good algorithms.. I am envisioning 3 situations. If the value is zero or single digit, if it is of odd length, and if it is of even length. I was planning to write for loops...
PS: The problem is: Find the highest value product of two 3 digit integers that is also a palindrome.
A pythonic way to determine if a given value is a palindrome:
str(n) == str(n)[::-1]
Explanation:
We're checking if the string representation of n equals the inverted string representation of n
The [::-1] slice takes care of inverting the string
After that, we compare for equality using ==
An alternative to the rather unintuitive [::-1] syntax is this:
>>> test = "abcba"
>>> test == ''.join(reversed(test))
True
The reversed function returns a reversed sequence of the characters in test.
''.join() joins those characters together again with nothing in between.
Just for the record, and for the ones looking for a more algorithmic way to validate if a given string is palindrome, two ways to achieve the same (using while and for loops):
def is_palindrome(word):
letters = list(word)
is_palindrome = True
i = 0
while len(letters) > 0 and is_palindrome:
if letters[0] != letters[(len(letters) - 1)]:
is_palindrome = False
else:
letters.pop(0)
if len(letters) > 0:
letters.pop((len(letters) - 1))
return is_palindrome
And....the second one:
def is_palindrome(word):
letters = list(word)
is_palindrome = True
for letter in letters:
if letter == letters[-1]:
letters.pop(-1)
else:
is_palindrome = False
break
return is_palindrome
The awesome part of python is the things you can do with it. You don't have to use indexes for strings.
The following will work (using slices)
def palindrome(n):
return n == n[::-1]
What it does is simply reverses n, and checks if they are equal. n[::-1] reverses n (the -1 means to decrement)
"2) My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?"
Regarding the above, you want to use xrange instead of range (because range will create an actual list, while xrange is a fast generator)
My opinions on question 3
I learned C before Python, and I just read the docs, and played around with it using the console. (and by doing Project Euler problems as well :)
Below the code will print 0 if it is Palindrome else it will print -1
Optimized Code
word = "nepalapen"
is_palindrome = word.find(word[::-1])
print is_palindrome
Output:
0
word = "nepalapend"
is_palindrome = word.find(word[::-1])
print is_palindrome
Output:
-1
Explaination:
when searching the string the value that is returned is the value of the location that the string starts at.
So when you do word.find(word[::-1]) it finds nepalapen at location 0 and [::-1] reverses nepalapen and it still is nepalapen at location 0 so 0 is returned.
Now when we search for nepalapend and then reverse nepalapend to dnepalapen it renders a FALSE statement nepalapend was reversed to dnepalapen causing the search to fail to find nepalapend resulting in a value of -1 which indicates string not found.
Another method print true if palindrome else print false
word = "nepalapen"
print(word[::-1]==word[::1])
output:
TRUE
There is also a functional way:
def is_palindrome(word):
if len(word) == 1: return True
if word[0] != word[-1]: return False
return is_palindrome(word[1:-1])
I know that this question was answered a while ago and i appologize for the intrusion. However,I was working on a way of doing this in python as well and i just thought that i would share the way that i did it in is as follows,
word = 'aibohphobia'
word_rev = reversed(word)
def is_palindrome(word):
if list(word) == list(word_rev):
print'True, it is a palindrome'
else:
print'False, this is''t a plindrome'
is_palindrome(word)
There is much easier way I just found. It's only 1 line.
is_palindrome = word.find(word[::-1])
The most pythonic way to do this is indeed using the slicing notation to reverse the string as mentioned already:
def is_palindrome(string: str) -> bool:
return string == string[::-1]
In some other occasions though (like technical interviews), you may have to write a "proper" algorithm to find the palindrome. In this case, the following should do the trick:
def is_palindrome(string: str) -> bool:
start = 0
end = len(string) - 1
while end >= start:
if string[end] != string[start]:
return False
start += 1
end -= 1
return True
Set pointers to the start and end of the string
Iterate while end exceeds start
If the character in end and start indices don't match then this is not a palindrome, otherwise keep comparing
Increase start pointer by 1
Decrease end pointer by 1
Test Cases:
import unittest
class Test(unittest.TestCase):
palindromes = ['a', 'aa', 'aba', '12321']
non_palindromes = ['ab', 'aab', 'cacacc']
def test_is_palindrome(self):
for case in self.palindromes:
self.assertTrue(is_palindrome(case))
for case in self.non_palindromes:
self.assertFalse(is_palindrome(case))
if __name__ == '__main__':
unittest.main()
You could use this one-liner that returns a bool value:
str(x)==str(x)[::-1]
This works both for words and numbers thanks to the type casting...
Here a case insensitive function since all those solutions above are case sensitive.
def Palindrome(string):
return (string.upper() == string.upper()[::-1])
This function will return a boolean value.
doing the Watterloo course for python, the same questions is raised as a "Lesseon" find the info here:
http://cscircles.cemc.uwaterloo.ca/13-lists/
being a novice i solved the problem the following way:
def isPalindrome(S):
pali = True
for i in range (0, len(S) // 2):
if S[i] == S[(i * -1) - 1] and pali is True:
pali = True
else:
pali = False
print(pali)
return pali
The function is called isPalindrome(S) and requires a string "S".
The return value is by default TRUE, to have the initial check on the first if statement.
After that, the for loop runs half the string length to check if the character from string "S" at the position "i" is the same at from the front and from the back.
If once this is not the case, the function stops, prints out FALSE and returns false.
Cheers.kg
If the string has an uppercase or non-alphabetic character then the function converts all characters to lowercase and removes all non-alphabetic characters using regex finally it applies palindrome check recursively:
import re
rules = [
lambda s: any(x.isupper() for x in s),
lambda s: not s.isalpha()
]
def is_palindrome(s):
if any(rule(s) for rule in rules):
s = re.sub(r'[^\w]', '', s).lower()
if len(s) < 2:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
string = 'Are we not drawn onward, we few, drawn onward to new era?'
print(is_palindrome(string))
the output is True for the input above.
maybe you can try this one:
list=input('enter a string:')
if (list==list[::-1]):
print ("It is a palindrome")
else:
print("it is not palindrome")
You are asking palindrome in python. palindrome can be performed on strings, numbers and lists. However, I just posted a simple code to check palindrome of a string.
# Palindrome of string
str=raw_input("Enter the string\n")
ln=len(str)
for i in range(ln/2) :
if(str[ln-i-1]!=str[i]):
break
if(i==(ln/2)-1):
print "Palindrome"
else:
print "Not Palindrome"
The real easy way to do that it is
word = str(raw_input(""))
is_palindrome = word.find(word[::-1])
if is_palindrome == 0:
print True
else:
print False
And if/else here just for fancy looks. The question about palindrome was on Amazon's interview for QA
Assuming a string 's'
palin = lambda s: s[:(len(s)/2 + (0 if len(s)%2==0 else 1)):1] == s[:len(s)/2-1:-1]
# Test
palin('654456') # True
palin('malma') # False
palin('ab1ba') # True
word = "<insert palindrome/string>"
reverse = word[::-1]
is_palindrome = word.find(reverse)
print is_palindrome
This was a question in Udacity comp 101, chapter 1. Gives a 0 for palindrome gives a -1 for not. Its simple, and does not use loops.
I wrote this code:
word = input("enter: ")
word = ''.join(word.split())`
for x in range(len(word)):
if list(word)[x] == ((list(word)[len(word)-x-1])):
if x+1 == len(word):
print("its pali")
and it works.
it gets the word, then removes the spaces and turns it into a list
then it tests if the first letter is equal to the last and if the 2nd is equal to 2nd last and so on.
then the 'if x+1 == len(word)' means that since x starts at 0 it becomes 1 and then for every next .. blah blah blah it works so it works.
#compare 1st half with reversed second half
# i.e. 'abba' -> 'ab' == 'ba'[::-1]
def is_palindrome( s ):
return True if len( s ) < 2 else s[ :len( s ) // 2 ] == s[ -( len( s ) // 2 ):][::-1]
You can use Deques in python to check palindrome
def palindrome(a_string):
ch_dequeu = Deque()
for ch in a_string:
ch_dequeu.add_rear(ch)
still_ok = True
while ch_dequeu.size() > 1 and still_ok:
first = ch_dequeu.remove_front()
last = ch_dequeu.remove_rear()
if first != last:
still_ok = False
return still_ok
class Deque:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def add_rear(self, item):
self.items.insert(0, item)
def add_front(self, item):
self.items.append(item)
def size(self):
return len(self.items)
def remove_front(self):
return self.items.pop()
def remove_rear(self):
return self.items.pop(0)
import string
word = input('Please select a word to test \n')
word = word.lower()
num = len(word)
x = round((len(word)-1)/2)
#defines first half of string
first = word[:x]
#reverse second half of string
def reverse_odd(text):
lst = []
count = 1
for i in range(x+1, len(text)):
lst.append(text[len(text)-count])
count += 1
lst = ''.join(lst)
return lst
#reverse second half of string
def reverse_even(text):
lst = []
count = 1
for i in range(x, len(text)):
lst.append(text[len(text)-count])
count += 1
lst = ''.join(lst)
return lst
if reverse_odd(word) == first or reverse_even(word) == first:
print(string.capwords(word), 'is a palindrome')
else:
print(string.capwords(word), 'is not a palindrome')
the "algorithmic" way:
import math
def isPalindrome(inputString):
if inputString == None:
return False
strLength = len(inputString)
for i in range(math.floor(strLength)):
if inputString[i] != inputString[strLength - 1 - i]:
return False
return True
There is another way by using functions, if you don't want to use reverse
#!/usr/bin/python
A = 'kayak'
def palin(A):
i = 0
while (i<=(A.__len__()-1)):
if (A[A.__len__()-i-1] == A[i]):
i +=1
else:
return False
if palin(A) == False:
print("Not a Palindrome")
else :
print ("Palindrome")
It looks prettier with recursion!
def isPalindrome(x):
z = numToList(x)
length = math.floor(len(z) / 2)
if length < 2:
if z[0] == z[-1]:
return True
else:
return False
else:
if z[0] == z[-1]:
del z[0]
del z[-1]
return isPalindrome(z)
else:
return False
def is_palindrome(string):
return string == ''.join([letter for letter in reversed(string)])
print ["Not a palindrome","Is a palindrome"][s == ''.join([s[len(s)-i-1] for i in range(len(s))])]
This is the typical way of writing single line code
def pali(str1):
l=list(str1)
l1=l[::-1]
if l1==l:
print("yess")
else:
print("noo")
str1="abc"
a=pali(str1)
print(a)
I tried using this:
def palindrome_numer(num):
num_str = str(num)
str_list = list(num_str)
if str_list[0] == str_list[-1]:
return True
return False
and it worked for a number but I don't know if a string
def isPalin(checkWord):
Hsize = len(lst)/2
seed = 1
palind=True
while seed<Hsize+1:
#print seed,lst[seed-1], lst [-(seed)]
if(lst[seed-1] != lst [-seed]):
palind = False
break
seed = seed+1
return palind
lst = 'testset'
print lst, isPalin(lst)
lst = 'testsest'
print lst, isPalin(lst)
Output
testset True
testsest False

Python, checking if string consists only of 1's and 0's

I'm trying to write a function that checks if given string is binary or not. I'm using a while loop to browse characters in string one by one. If all of them are 0's or 1's it's going to return True, if anything is not - break the loop and return False.
I've just written this tiny part of code, but it doesn't run. Why?
def fnIsBin(string):
count = 0
while count < len(string):
character = string[count]
if character == '0' or character == '1':
print (count, character[count], "OK")
count = count+1
continue
else:
print (count, character[count], "ERROR")
return False
break
EDIT:
I also tried using 'set' to elude iterating with loop, but i don't quite get how does "set(string)" work. I got error that i cant consider it as a list. So how can I compare elements to 0 & 1?
def fnIsBin(string):
charactersList = set(string)
if len(charactersList) > 2:
return False
else:
if (charactersList[0] == '0' or charactersList[0] == '1') and (charactersList[1] == '0' or charactersList[1] == '1'): #there i made error, how to deal with it?
return True
else:
return False
Your function fails because you never actually return True. That means if the string is actually binary, you'd return None which Python would consider as False in any boolean check.
Simply add return True at the end of the function.
As #Barmar mentioned in the comment, you also print the value of character[count] instead of string[count] which would cause IndexError.
An easier way to check if the string is binary would be:
test_string = '010101'
all_binary = all(c in '01' for c in test_string)
There are many ways to do this:
Set:
fnInBin(s):
return set(s).issubset({'0', '1'}) and bool(s)
Regular expression:
fnInBin(s):
return bool(re.fullmatch('[01]+', s))
Integer conversion:
fnIsBin(s):
try:
int(s, 2)
return True
except ValueError:
return False
The last one will strip whitespace from the input, though.
fnIsBin('\n 1 ') == True
You can use the int object and give it a base. It will fail if the object passed doesn't consist of a binary representation. Recall that a binary string is base 2.
def fnIsBin(string):
try:
binary_repr = int(string, 2)
except ValueError as err
print("error: {0}".format(err))
return False
return True
You're printing OK for each character that's 0 or 1, even though there may be a later character that isn't. You need to wait until the end of the loop to know that it's really OK.
def fnIsBin(string):
for character in string:
if character != '0' and character != '1':
print (character, "ERROR")
return False
print "OK"
return True
There's no need for break after return False -- returning from the function automatically breaks out of the loop.
Here's one of the ways you could rewrite your function and maintain a similar structure (looping through each character):
def fnIsBin(string):
for character in string:
if not character in '01':
return False
return True
You could also do it using regular expressions:
import re
def fnIsBin(string):
return re.match(r'^[10]+$', '01') is not None
My two cents (A short way):
test_string = '010101'
result = set(test_string) <= {'0','1'}
print(result)
Using set(test_string) converts the string into list of characters,
{0,1,0,1,0,1}
Using <= operator checks whether the set on the left-side is a proper subset of the set on the right-hand side
Ultimately checking whether there are only 0 and 1 are in the string or not in an in-direct and mathematical way.
Adding a XOR solution to the mix:
bin_string = '010101'
for j in range(0, len(bin_string)):
if int(bin_string[j]) != 0 ^ int(bin_string[j]) != 1:
break

Python: Recursive Function to check if string is a palindrome

So I'm trying to create a recursive function to check if a word is a palindrome. It should ignore all non-alphabetical characters. Here is what I have so far.
def is_palindrome(text):
'''
A Recursive Function that returns True if the parameter, text, is a palindrome, False if not.
Ignores capitalization, punctuation, and spaces.
text: a String
returns True or False
'''
text = list(text)
if len(text) == 0:
return True
else:
if text[0].isalpha():
if text[-1].isalpha():
if text[0].lower() == text[-1].lower():
text.remove(text[0])
text.remove(text[-1])
return is_palindrome(text)
else:
return False
else:
text.remove(text[-1])
return is_palindrome(text)
else:
text.remove(text[0])
return is_palindrome(text)
Here are some test cases...
is_palindrome("abcde")
Results
abcde
False
is_palindrome("aabbaa")
Results
aabbaa
['b', 'b', 'a', 'a']
False
is_palindrome("aa bb cc")
Results
aa bb aa
[' ', 'b', 'b', ' ', 'a', 'a']
['b', 'b', ' ', 'a', 'a']
False
So for some reason, it always directly ends up being false.
Thoughts on how to solve this? All help will be appreciated!
text.remove(text[0]) does not do what you think it does (It removes the first occurrence of that value from the list). To remove by index use slices. You can rewrite this:
text.remove(text[0])
text.remove(text[-1])
to this:
text = text[1:-1]
Is this just for fun, or an exercise? I don't think recursion really makes sense here:
def palindrome(s):
l = len(s)
m = l // 2
return s[:m][::-1] == s[m + (l % 2):]
Then I'd just preprocess the input to remove non alphanumerics and uppers like:
s = 'aBc%$cbA'
palindrome(re.subn('\W', '', s)[0].lower())
From the Python 3 documentation:
list.remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.
When you call text.remove(text[-1]) for the list based on the string aabbaa, the first a in the list will be removed, which is not always the desired behavior. If you want to remove the first and last elements of the list, you can use a slice as user1434070 posted. An alternate method is to use list.pop(x) to remove the element with a specified index, which is accomplished by replacing the calls to remove with the following code:
text.pop(0)
if len(text) == 0:
return True
text.pop(-1)
Note that the size of the list must be checked after the first pop in case it contained a single letter. This occurs in the deepest level of recursion when the original palindrome contains an odd number of characters.
list.remove() removes the first occurrence of an element in the list. If that element is present at the beginning and end, it doesn't matter that you selected that element by indexing the list to get the last element - it'll still remove the first one it sees. list.pop() would be more appropriate, as that removes elements based on their index rather than their value.
def is_palindrome(text):
text = list(text)
if len(text) == 0:
return True
else:
if text[0].isalpha():
if text[-1].isalpha():
if text[0].lower() == text[-1].lower():
text.pop(0)
text.pop()
return is_palindrome(text)
else:
return False
else:
text.pop()
return is_palindrome(text)
else:
text.pop(0)
return is_palindrome(text)
However, you can further improve your program by filtering out any ignored characters at the beginning:
def is_palindrome(text):
text = ''.join(filter(str.isalpha, text)).lower()
if not text:
return True
text = list(text)
if text[0].lower() == text[-1].lower():
text.pop(0)
text.pop()
return is_palindrome(text)
return False
A further optimization would be to use a default argument to note whether the string has been cleaned already, and send a slice to the recursive call:
def is_palindrome(text, cleaned=False):
if not cleaned:
text = ''.join(filter(str.isalpha, text)).lower()
if not text:
return True
if text[0] != text[-1]:
return False
return is_palindrome(text[1:-1], 1)

Python 3.2 palindrome

I'm doing some python online tutorials, and I got stuck at an exercise:A palindrome is a word which is spelled the same forwards as backwards. For example, the word
racecar
is a palindrome: the first and last letters are the same (r), the second and second-last letters are the same (a), etc. Write a function isPalindrome(S) which takes a string S as input, and returns True if the string is a palindrome, and False otherwise.
These is the code I wrote :
def isPalindrome(S):
if S[0] == S[-1]
return print("True")
elif S[0] == S[-1] and S[1] == S[-2] :
return print("True")
else:
return print("False")
But, if the word is for example ,,sarcas,, , the output is incorect. So I need a fix to my code so it works for any word.
A one line solution but O(n) and memory expensive is :
def isPalindrome(word) : return word == word[::-1]
A O(n/2) solution that uses the same amount of memory is:
def palindrome(word):
for i in range(len(word)//2):
if word[i] != word[-1-i]:
return False
return True
This is the trick #LennartRegebro mentioned
def is_palindrome(text):
text = text.replace(' ', '')
text = text.casefold()
if list(text) == list(reversed(text)):
return True
else:
return False
Try this
word='malayalam'
print(word==word[::-1])
The best way to check a word is palindrome or not in Python is as below:
var[::] == var[::-1]
But, it is very important to understand that Python creates a new copy of string when you do var[::-1]
Python internally don't know if the reverse will result in same string or not. So, it's coded in a way where it creates a new copy of it.
So, when you try var[::1] is var[::-1] you will get FALSE.
Here is my solution.
S = input("Input a word: ")
def isPalindrome(S):
for i in range(0, len(S)):
if S[0 + i] == S[len(S) - 1]:
return "True"
else:
return "False"
print(isPalindrome(S))
Here's my solution:
def isPalindrome(S):
l = len(S)-1
for i in range(0,l):
if S[i]!=S[l-i]:
return False
return True
Another way of doing it using recursion is:
def isPalindrome(word):
if len(word) <= 1: return True
return (word[0] == word[-1]) and isPalindrome(word[1:-1])
this is my solution
S = input("Input a word: ")
def isPalindrome(S):
for i in range(0, len(S)):
if S[0 + i] == S[len(S) - 1]:
return "True"
else:
return "False"
print(isPalindrome(S))
This is beaten to death, but I have some ideas if Python is implemented in C. If ...
The code word[::-1] iterates to string end to make a copy which discounts the word == word[::-1] code speed and memory efficiency factors
Iteration to the word middle is better then comparing a full word as characters were already tested - for odd words the middle letter is not to be tested
Additions and subtractions need to be used sparingly
Recursion is cool (and fun), but uses a lot of stack (unless optimized with tail recursion ... which likely becomes a for loop in the underlying code but less likely able to be flexible enough to impose code optimizations).
Bit shifts are traditionally faster than divides
The following is the code:
def isPalindrome(S):
last = len(S)
middle = last >> 1
for i in range(middle):
last -= 1
if(S[i] != S[last]):
return False
return(True)
print("\n".join([str((word, isPalindrome(word))) for word in ["abcdcba", "abcdBba", "abccba", "abcBba", "a", ""]]))
which yields:
('abcdcba', True)
('abcdBba', False)
('abccba', True)
('abcBba', False)
('a', True)
('', True)

Single word Palindrome Checker (True or False)

Right now, what I have is a code that I can test a single word whether it is a Palindrome or not. I have to input the word, and it will tell me whether it is a Palindrome (True) or if it is not (False)
I need to create one that Asks for a single word, then provides a True of False based on the word that is typed. This is what i have so far.
I really have no idea how to do this, any help would be greatly appreciated.
def isPalindrome(s):
if len(s) <= 1:
return True
else:
if s[0] != s[len(s)-1]:
return False
else:
return isPalindrome(s[1:len(s)-1])
print(isPalindrome("poop"))
Simply create a reversed string and check if both are equal.
def isPalindrome(s):
return s == s[::-1]
print(isPalindrome('poop'))
Also using a reversed string, but can be used in-line, as well (i.e., doesn't require a function).
def is_palindrome(word):
return word == ''.join(reversed(word))
print is_palindrome('hello') #False
print is_palindrome('racecar') #True
If you are asking how to get Python to take user input, then there are a couple options available to you. One option is to make your script run from the command line and use a command line argument and the other is to use the raw_input function. Both are implemented in the following code.
import sys
def isPalindrome(word):
...
if __name__ == '__main__':
if len(sys.argv) > 1:
inp = sys.argv[1]
else:
inp = raw_input("Type a word: ") # Which you might want to strip for white space
if isPalindrome(inp):
print inp,"is a palindrome"
else:
print inp,"is not a palindrome"
Several other people have suggested alternative implementations for isPalindrome that are probably better, but if you are doing this as an assignment and are supposed to use recursion, then keep using yours. Also, the raw_input function can be called anywhere that is convenient in your script and doesn't have to be used when called from the command line.
You might try this function:
def is_palindrome(text):
return text[:len(text)//2] == text[:(len(text)-1)//2:-1]
Here is example usage for reference:
>>> is_palindrome('')
True
>>> is_palindrome('a')
True
>>> is_palindrome('b')
True
>>> is_palindrome('aa')
True
>>> is_palindrome('ab')
False
>>> is_palindrome('ba')
False
>>> is_palindrome('bb')
True
>>> is_palindrome('aaa')
True
>>> is_palindrome('aab')
False
>>> is_palindrome('aba')
True
here is mine:
def isPalindrome(word):
word=str(word)
a=word[::-1]
if a!=word:
return False
elif word=='':
return False
else: return True
Using string subscripting
def is_palindrome(string):
return all(char == string[-i - 1] for i, char in enumerate(string))
Using list reversing
def is_palindrome(string):
to_list = list(string)
# reverse to_list now
to_list.reverse()
# our reversed list should be equal string as a list
# if string is a palindrome
return to_list == list(string)
This is mine:
def palindrome_checker(word):
return True if len(word) < 2 else (word[0] == word[-1]) and palindrome_checker(word[1:-1])
This should work.
return (s[:1+len(s)//2]==s[len(s)//2:][::-1])
For the people doing the palindrome test from testdome.com that takes into account casing, here is my solution:
def is_palindrome(word):
wordoriginal = []
wordreversed = []
for i in reversed(word):
i = i.lower()
wordreversed.append(i)
for i in word:
i = i.lower()
wordoriginal.append(i)
return wordoriginal == wordreversed
This is what I came up with, hope it works for you:
def palindrome_(word):
word = input("enter your word Here ")
return word == word[::-1]
print palindrome_("word")

Categories

Resources