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")
Related
I am trying to make a script that checks if input is a palindrome or not. I'm confused as to why neither of them work. In the first attempt, I printed reversed_phrase but it printed <list_reverseiterator object at 0x000001DDD1E27D60>. In the second attempt, I printed phrase[i] and reverse_phrase[i] in each iteration and they printed the same thing.
First Attempt:
original_phrase = input()
phrase = list(original_phrase)
reversed_phrase = reversed(phrase)
if phrase == reversed_phrase:
print(original_phrase, 'is a palindrome')
else:
print(original_phrase, 'is not a palindrome')
Second Attempt:
original_input= input()
phrase = list(original_input)
reversed_phrase = phrase
reversed_phrase.reverse()
is_palindrome = False
for i in range(0, len(phrase)):
print(phrase[i], reversed_phrase[i])
if phrase[i] != reversed_phrase[i]:
break
elif i >= len(phrase) - 1:
is_palindrome = True
if is_palindrome:
print(original_input, 'is a palindrome')
else:
print(original_input, 'is not a palindrome')
Your first solution is misusing the reversed(array) function as it returns a pointer to the end of the array so that you can iterate through it in reverse. What you want here is to actually reverse the array which is done with array.reverse();
Your second solution incorrectly always returns true because when you do this: reversed_phrase = phrase both reversed_phrase and phrase reference the same object, so any changes made to one appear when referencing either. What you want to do is reversed_phrase = phrase.copy() so that they are each individual versions of the array
I am trying to create a code in which python asks the user for input or a word and it has to check whether it's a palindrome or not using recursion. If the word is not a palindrome through the reverse() function it will take in the string and, through recursion, return that string in reverse. It seems that I am able to take input and when I put in a word that's not a palindrome it gives me back the output needed. However it doesn't give back the word in reverse and also when I put a word that is a palindrome and it doesn't give the input back leaving a blank space in the output.
def reverse(choice, index, new_word):
if index < 0:
return new_word
else:
new_word += choice[index]
return reverse (choice, index - 1, new_word)
def palindrome():
new_word = ""
choice = input("Please enter a word to check if it is palindrome:")
result = reverse(choice, len(choice) - 1, new_word)
if result == choice:
print("That word",choice,"IS a palindrome")
else:
print("Sorry,",new_word,"is NOT a palindrome")
palindrome()
This is happening because you have set new_word to an empty string, and then you're taking the result of reverse() and storing that in another variable called result.
This should fix your issue:
def palindrome():
new_word = ""
choice = input("Please enter a word to check if it is palindrome:")
result = reverse(choice, len(choice) - 1, new_word)
if result == choice:
print("That word",choice,"IS a palindrome")
else:
# change here to result
print("Sorry,",result,"is NOT a palindrome")
Alternatively, you can use choice[::-1] to reverse a string. it is cleaner and you don't have to use recursion. However, the above fix will help you with the recursion bit as well.
Try the following:
def check_palindrome(word): # Creating function with 1 parameter: word
if word == word[:: -1]: # word[:: -1] reverses a string
return True # Return a true value if word is the same when reversed
else:
return False # Otherwise, return a false value
print(check_palindrome("racecar")) # Palindrome
print(check_palindrome("hello world")) # Not a palindrome
the syntax word[:: -1] reverses the word.
I am trying to determine if a given word is a palindrome.
The goal of my code is that the function will take a word, and remove it of any punctuation or spaces. If the length of the word is 0 or 1, it is returned that the word is a palindrome. I then check if the first and last letter are the same. If they aren't, it is returned that it is not a palindrome. If they first and last letters the same, I then want to replace those two letters with spaces and call my function again. The reason I replace the letters with spaces is so that it will be edited by my initial edit statements.
def palindrome(word):
editWord = word.strip(" ").strip("!").strip("?")
stringOne = "A palindrome"
stringTwo = "Not a palindrome"
if len(editWord) == 0 or len(editWord) == 1:
return stringOne
elif editWord[0] != editWord[-1]:
return stringTwo
else:
word = editWord.replace(editWord[0], " ").replace(editWord[-1], " ")
palindrome(word)
return stringOne
print(palindrome("area"))
When tested with single letters it functions properly, as well if I test words like 'are' which obviously is not a palindrome. However, if I call the word area it returns "A palindrome" when it is not. This makes it seem like it is not calling my function again. Any suggestions on why this is happening?
For recursion to work properly here, your else statement should say something along the lines of "the word is a palindrome if the outer characters are equal and the remainder is also a palindrome". Instead, your code is replacing all occurrences of the outer characters with spaces, checking if the word is a palindrome, and ignoring the result to always return "yes".
You can do a proper recursion using slicing instead of replacement:
else:
return palindrome(editWord[1:-1])
Another alternative to replacing the letters while still doing this recursively to to keep track of the index in the word and increment it on recursion. This saves you from having to make new slices on each recursion. In this case your edge case will be when the index is in the middle of the word.
def palindrome(word, i = 0):
if i >= len(word)//2:
return True
if word[i] != word[-(i+1)]:
return False
return palindrome(word, i+1)
palindrome("mrowlatemymetalworm") # true
So I'm trying to check if a word is a palindrome using stacks. I've gotten it work with one exception. If I try the word 'level' it works, however, if I try 'levell' it comes back true. Here's my code:
import Stack
def check_palindrome():
s = Stack.Stack()
word = input('Enter a word: ')
for x in word:
s.push(x)
palindrome = True
for x in range(len(word)):
if s.pop() == word[x]:
palindrome = True
else:
palindrome = False
if palindrome == True:
print(word, 'is a palindrome.')
else:
print(word, 'is not a palindrome.')
check_palindrome()
I can't seem to figure out why it is saying it's true. Maybe I'm thinking about this incorrectly. My train of thought was to add each letter to the stack using
for x in word:
s.push(x)
Then to pop it because of FILO and compare the last to the first. Any insight would be appreciated!
Of course, there are much better ways to check that a word is a palindrome, using reversed string and comparing to itself for instance (there are a ton of answers on this site solving this).
That said, about your problem:
for x in range(len(word)):
if s.pop() == word[x]:
palindrome = True
else:
palindrome = False
If one letter doesn't match, it should break the loop, or else the answer is conditioned only by the last loop iteration. I'd write:
for letter in word:
if s.pop() != letter:
palindrome = False
break # one mismatch: bail out
else:
palindrome = True # OK
(else of the for loop is executed only if all iterations were achieved without encountering break)
I don't know if you intentionally want to use Stack, why not check if the word is equal to its reverse, like so?
def check_palindrome(word):
palindrome = word == word[::-1] # True if word is equal to its reverse
if palindrome == True:
print(word, 'is a palindrome.')
else:
print(word, 'is not a palindrome.')
The problem is that your comparison continues even after you find a mismatch, so palindrome can get reset to True even after it gets set to False. So overall, you're actually only checking if the first and last letter of your word is the same. You can fix this by breaking out of the loop when you find a mismatch.
Also just as a style note, you can replace if palindrome == True: with if palindrome:
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]