Palindrome Function Python - python

I'm trying to write a function that will tell me if the inputted word or phrase is a palindrome. So far my code works but only for single words. How would I make it so that if I enter something with a space in it like 'race car' or 'live not on evil' the function will return true? Other questions on this page explain how to do it with one words but not with multiple words and spaces. Here what I have so far...
def isPalindrome(inString):
if inString[::-1] == inString:
return True
else:
return False
print 'Enter a word or phrase and this program will determine if it is a palindrome or not.'
inString = raw_input()
print isPalindrome(inString)

You could add the characters of the string to a list if the character is not a space. Here is the code:
def isPalindrome(inString):
if inString[::-1] == inString:
return True
else:
return False
print 'Enter a word or phrase and this program will determine if it is a palindrome or not.'
inString = raw_input()
inList = [x.lower() for x in inString if x != " "] #if the character in inString is not a space add it to inList, this also make the letters all lower case to accept multiple case strings.
print isPalindrome(inList)
Output of the famous palindrome "A man a plan a canal panama" is True. Hope this helps!

You just need to split it by the spaces and join again:
def isPalindrome(inString):
inString = "".join(inString.split())
return inString[::-1] == inString

Slightly different approach. Just remove spaces:
def isPalindrome(inString):
inString = inString.replace(" ", "")
return inString == inString[::-1]

Related

Removing non alpha numeric characters from string and splitting strings words into a list to see if a condition has been met using regular expressions

I am completing a program that takes a sys argument(string) and checks if it's a palindrome or not. My current code works if I have a single-word string. However, I need to make sure the program would check each individual word and not factor in any non alphanumeric characters. If any of the words are a palindrome then it would print it's a palindrome a single time.
Thought process:
My thoughts were to split each word into a list, have the list iterated to see if the condition has been met, and print only one time. If I have multiple words it prints out it's not a palindrome. Currently, it will just print it's not a palindrome multiple times if I provide a string with multiple words: ie 'racecar, racecar'
Any suggestions would be much appreciated.
Here is my code so far;
def palindrome():
string = sys.argv[1].lower()
remove_punc = string.strip('~`!#$%^&*()_-+={}[]|\:;<,>.?/')
converted_string = remove_punc.split(' ')
for i in converted_string:
if converted_string == converted_string[::-1]:
print('It\'s a palindrome!')
break
else:
print('It\'s not a palindrome!')
palindrome()
When you enter more than 1 word (thing with a space before or after),
you need to take all the arguments but the program itself, if your want to have each word. Then you clean them from non alpha chars, then you can test them.
import sys
def palindromes():
words = sys.argv[1:]
cleaned_words = [
w.strip('~`!#$%^&*()_-+={}[]|\:;<,>.?/')
for w in words
]
for word in cleaned_words:
if word == word[::-1]:
print(f'{word} is a palindrome!')
else:
print(f'{word} is not a palindrome!')
palindromes()
Test:
$ python palindromes.py foo aba bar boob
foo is not a palindrome!
aba is a palindrome!
bar is not a palindrome!
boob is a palindrome!
Do you mean this?
import re
s = "aaa bbb, aaa"
s = re.sub("[^A-z]", "", s)
print(s == s[::-1])
Update
With no regex:
s = "Al lets Della call Ed “Stella.”"
s = "".join([x for x in s.lower() if 123>ord(x)>96])
print(s == s[::-1])
To work with args:
s = sys.argv[1]
s = "".join([x for x in s.lower() if 123>ord(x)>96])
print(s == s[::-1])
Update 2
If you want to check several palindromes at once, here you go:
import sys
for s in sys.argv[1:]:
x = "".join([x for x in s.lower() if 123>ord(x)>96])
print("'"+ s + "' is a palindrome? ", x == x[::-1])
I appreciate the submissions and this is the main part that worked for me.
new_string = ''.join(i if i.isalpha() else '' for i in string)
if new_string == new_string[::-1]:
print('It\'s a palindrome!')
else:
print('It\'s not a palindrome!')

checking if a string is a palindrome not working properly

For some reason it works great but on some sentences that are palindrome it says they are not
palindrome = input("Enter a word: ")
palindrome = palindrome.lower()
palindrome.replace(" ", "")
if palindrome == palindrome[::-1]:
print("OK")
else:
print("NOT")
An example:"Mr Owl ate my metal worm"
but on other sentences it works good and i don't understand whats different
please help me btw the level of the code needs to be at this level
instead of using replace whitespace ( if they are not require much ) then, you can convert the word to list of words sperated on whitespace and then create a new word joining all word inside the list and reverse it to check if the sentence is palindrome or not
here is code
palindrome = input("enter the word ")
palindrome = ''.join(palindrome.split()).lower()
if palindrome == palindrome[::-1]:
print("OK")
else:
print("NOT")
without using join
palindrome = input("enter the word ")
new_palin = ''
for chars in palindrome:
if chars != ' ' :
new_palin+=chars
new_palin = new_palin.lower()
if new_palin == new_palin[::-1]:
print("OK")
else:
print("NOT")

How to check a string for elements in an array in python 3.4

Lets say I have the following variables...
bad_words = ['bad0', 'bad1', 'bad2']
bad_string = "This string has bad1 in it."
bad_string2 = "This string is abcbad0xyz."
good_string = "This string is good!"
What's the best way to look through the strings for the 'bad words' and only print out the good string?
Example...
def check_words(string):
bad_words = ['bad0', 'bad1', 'bad2']
#this is where I need help...
#Return False if string contains any of the words in bad words
#Return True if string does not contain bad words.
bad_string = "This string has bad1 in it."
good_string = "This string is good!"
#call the check_words method by sending one of the strings
valid = check_words(bad_string) #I want this to return False
if valid:
print("Good string!")
else:
print("Bad string!")
#or...
valid = check_words(good_string) #I want this to return True
if valid:
print("Good string!")
else:
print("Bad string!")
This is pretty straight forward, iterate through the bad_words and check if word is in string, and return False if it is. After we check all the bad_words we can return True safely.
def check_words(string):
bad_words = ['bad0', 'bad1', 'bad2']
for word in bad_words:
if word in string:
return False
return True
You can use the builtin function any() to test if any "bad words" are in your strings:
def check_words(string, words):
return any(word in string for word in words)
string would be you string for testing, and words would be your list of bad words. This works by testing if any word from the words list is in your string. The any() function then returns a boolean based upon your conditions.
You can use regular expressions to match any of the bad words:
is_bad = re.search('|'.join(bad_words), bad_string) != None
bad_string is the string to test, is_bad is True or False, depending on whether bad_string has bad words or not.

How to check if a word is a palindrome (Python)

Please help...
So the instruction says to program the computer to check whether a word is a palindrome or not. I inputted this code:
def is_palindrome(word):
counter_from_first_letter=0
counter_from_last_letter=-1
from_first_letter = word[counter_from_first_letter]
from_last_letter = word[counter_from_last_letter]
max_index_from_first= len(word)
max_index_from_last= (len(word))*-1
while from_first_letter == from_last_letter:
from_first_letter = word[counter_from_first_letter]
from_last_letter = word[counter_from_last_letter]
counter_from_first_letter += 1
counter_from_last_letter -= 1
return True
The problem is the computer only checks whether the first and last letters are the same, and if they are, it just returns true. How do I make sure the computer checks every single letter? Thanks
Maybe something like this:
def is_palindrome(word):
if word == word[::-1]:
return True
else:
return False
in python-3
name = 'madam'
print(name.find(name[::-1]) == 0)
Maybe you can try this: first convert your string into a list, then reverse the list and convert it back into a string. compare both the strings and if they match? they are palindromes, if not, they aren't.
'''checking whether a word is a palindrome
we first convert the word into a list then join it;
use an if statement to compare the two strings'''
def palindrome(string):#you need the input(string)
palindrome_check=[]#create an empty list
for character in string [::-1]:#create a list from the input
#(use a for loop because you now know the range)
#the [::-1] analyzes the characters in reverse
palindrome_check.append(character)#add each character to the new empty list
#print(palindrome_check)
rev_string= ''.join(palindrome_check)#.join -creates a string from the created list
print(rev_string)
#REMOVE SPECIAL CHARACTERS- IM THINKING OF A LOOPING THROUGH, BUT NOT SURE HOW TO IMPLEMENT IT
string=string.replace(' ', '')
rev_string=rev_string.replace(' ', '')
string=string.replace(',', '')
rev_string=rev_string.replace(',', '')
string=string.replace('.', '')
rev_string=rev_string.replace('.', '')
#THIS IS THE LOGIC: IT CHECKS BOTH STRINGS, if they are equal, it is a palindrome;
if string.lower()==rev_string.lower():
return True, print('It is a Palindrome')
else:
return False, print('It isnt a palindrome')
#call the function; key in the parameters-
palindrome= palindrome("No, Mel Gibson Is A Casinos Big Lemon")
#maybe we can try having a user key in the parameter? lets try
#palindrome=palindrome(input('kindly enter your word/phrase '))-wrong
#print('Kindly enter your word or phrase')
#user_palindrome=input('')
#palindrome=palindrome(user_palindrome)
#it wont work this way either
If you can have the user define the parameter(string), the better, if you know how to do this, kindly share.
To check whether a word or phrase is a palindrome, it be necessary to check if the original sentence is equal to the original sentence reversed.
word = "Eva can I see bees in a cave"
word_lower = word.lower().replace(" ", "")
if word_lower == word_lower[::-1]:
print("It's a palindrome")
else:
print("This is not a palindrome")

Recursive Program: What am I doing wrong?

I am trying to write a code that would analyze if a word is a palindrome.
BTW a palindrome is a word that is read the same backward and forward. Example are "madam" or "noon"
Here is a try:
x = raw_input("please enter a word:\n")
L = len(x)
# this part returns the first letter of the word
def first(word):
return word[0]
# this part returns the last letter of the word
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(word):
if L <= 2:
print 'enter a word with at least three letters'
elif first(word) != last(word):
print 'This word is not a palindrome'
else:
word = middle(word)
is_palindrome(word)
is_palindrome(x)
But when executed, I get
IndexError: string index out of range
...line 7, in first return word[0]
The first branch of "is_palindrome" works perfectly. i.e. when the word is not a palindrome, I get no errors. Like "noopn" is executed with no errors, but the error is in the second branch
I've playing with this code for so many times but can't figure out the "iterative part" I have the answer but I don't want to look at it yet. I need to figure out two things:
1. a way to make the iteration in the function is_palindrome work correctly?
and 2. a way to exit the program in the end.
Could you folks direct me to how to answer these questions without providing the solution yet?
Finally where should I put the print statement: print 'This word is a palindrome'
Thank you
To accomplish your goal, why don't just use:
string[::-1] == string
And the reason for your answer is when there is only 1 letter, middle will return an empty string and then ''[0] will cause the error.
You need a base case for your recursion. A one letter word is a palindrome, and an empty string is also a palindrome.
def is_palindrome(word):
# handle the base case
if len(word) <= 1:
print 'This word is a palindrome'
elif first(word) != last(word):
print 'This word is not a palindrome'
else:
word = middle(word)
is_palindrome(word)
If you want to reject words with fewer than three letters, then you can use a helper function that calls the recursive function:
def is_palindromeHelper(word):
if len(word) <= 2:
print 'enter a word with at least three letters'
else:
is_palindrome(word)
Personally, I would prefer separating the check and the output. So is_palindrome() should just return the answer and not be responsible for telling the user. That makes it more reusable.
def is_palindrome(word):
# handle the base case
if len(word) <= 1:
return True
elif first(word) != last(word):
return False
else:
word = middle(word)
return is_palindrome(word)
This enables you to do
x = raw_input("please enter a word:\n")
L = len(x)
if L <= 2:
print 'enter a word with at least three letters'
elif is_plaindrome(word):
print 'This word is a palindrome'
else:
print 'This word is not a palindrome'
This puts the validity check to the front of the execution, while in the recursion, you have only the checks which are valid all over the recursion.
(I doubt if your check is necessary at all - are y and oo no palindromes? We could argue about the empty string, however...)
The next improvement steps could be to omit the functions first(), last() and middle() - they are trivial and only used once, so you could put there code where they are used.
Added an extra condition in your code , which will solve your problem. You don't need to call is_palindrome() , when you have just a single character left
x = raw_input("please enter a word:\n")
L = len(x)
# this part returns the first letter of the word
def first(word):
return word[0]
# this part returns the last letter of the word
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(word):
if L <= 2:
print 'enter a word with at least three letters'
elif first(word) != last(word):
print 'This word is not a palindrome'
else:
word = middle(word)
if len(word) > 1:
is_palindrome(word)
else:
print 'This word is a palindrome'
is_palindrome(x)
A basic version without considering capitalization and white-space, I'd suggest:
def is_palindrome(word):
if len(word) < 3:
print 'Enter a word with at least three letters'
else:
for letter in range(len(word)/2):
if word[letter] != word[-letter - 1]:
print "This word is not a palindrome"
return
print "This word is a palindrome"
Though I think it might personally remove white space and make the comparisons using .lower(). Then it will be case insensitive and allow for testing a phrase or sentence also.
Great directions guys. All got an upvote.
These directions allowed me to make the following concise codes
Code 1
x = raw_input("enter a word to check if it is a palindrome:\n")
if x[::-1] == x:
print 'yes this one is a palindrome'
else:
print 'sorry try again by re-running the program'
Code 2
x = raw_input("enter a word to check if it is a palindrome:\n")
if len(x) <= 1:
print 'Of course ', x, ' is a palindrome'
def is_palindrome(x):
if len(x) >= 2:
if x[0]!=x[-1]:
print 'This is not a palindrome'
else:
x = x[1:-1]
return is_palindrome(x)
print 'This is FINALLY a real palindrome'
is_palindrome(x)
I guess I could include the function is_palindrome as a second branch of the conditional statement len(x) <= 1, but I like it better this way since the code is all about this function

Categories