Python Palindrome Help: Count palindromes in a sentence - python

I have created a program in python that basically tells the user to enter a word and tells them if it's a palindrome or not.
My program:
def palindrome(word):
return word == word[::-1]
word = input("Enter a word: ")
word2 = word.lower()
if word2 == "":
print("You failed to input a word")
elif palindrome(word2) == True:
print(word2,"is a palindrome!")
else:
print(word2,"is not a palindrome!")
I need help modifying my program so that it allows the user to enter a sentence and counts the number of words in the sentence that are palindromes. When I execute the program I would want it to output the palindromes in the sentence.
I've been struggling with this for days and I can't seem to figure out where to start. Help would be much appreciated. Also, I need to MODIFY my program above, not make a completely different program.

You need to split the string into words then check if each word is a palindrome using a list comp, the length of the list will also give you the count:
def palindrome(word):
return word == word[::-1]
# split sentence into words and filter out the non palindromes
sentence = [w for w in input("Enter a sentence: ").split() if palindrome(w)]
print(" There are {} palindromes in your sentence\n.".format(len(sentence)))
# print each palindrome from our list
for pal in sentence:
print("{} is a palindrome".format(pal))
If you want to mimic your own code, keep a count as you iterate over the list of words increasing the count if we have a palindrome:
sentence = input("Enter a sentence: ").split()
count = 0
for w in sentence:
if palindrome(w):
count += 1
print("{} is a palindrome.")
else:
print("{} is not a palindrome.")
print(" There are {} palindromes in your sentence\n.".format(count))
To catch single non-letters:
def palindrome(word):
if len(word) > 1:
return word == word[::-1]
return word.isalpha()

Related

Can I print the input of a string for len not just the number of characters?

I'm trying to find find the longest string entered then print it as the output value. The program stops running when an 'a' has been entered then returns the longest string entered not just the numbers of characters in the string. Can the length function do this?
def longest_str(words):
words = len(words)
return words
true = 1
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
if words.startswith('a'): #comparing if starts with a or A
print(f"The longest string was: {longest_str(words)}") # printing output
break #stop once reached a
else:
continue # continue to loop through, no a was found.
I understand what you are trying to do but you have several mistakes
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
This will read only one word at the time.
So, your if will be executed only if you enter a word starting with 'a'.
This will solve your problem
def longest():
maxLength = 0
longestWord = ''
while(True):
word = str(input("Enter a string: "))
word = word.lower()
if word == 'a':
print(f"The longest string was: {longestWord}")
break
if len(word) > maxLength:
maxLength = len(word)
longestWord = word
Take a look at the differences
We check if the word entered is 'a', then print the longest string and stop.
If not, we check if the new word is longer than what we previously had (initialy nothing).If the new word is longer, we retain it to be able to print it.
Just call this in the main function.
If you want the string itself you could just do it like this:
longest_string = ''
while True:
word = input("Enter a string: ").lower()
if word == 'a': break
if len(word) > len(longest_string):
longest_string = word
print("The longest string was: " + longest_string)
Keep in mind, this will make ALL words lowercase, if you dont want that you have to remove the .lower()

How to return a result when for loop does not generate any result

HI I am trying to compare a word to the words data and checking whether the input word is a palindrome. For example, drawer is a palindrome, as its reverse reward is also a true word.
I have the following code-
words = sorted({line.strip().lower() for line in open('words.txt', 'r')})
# words is a standard English dictionary
def signature(word):
return ''.join(reversed(word))
def find_palindrom(myword):
mysig = signature(myword)
for word in words:
if mysig == word:
print(myword)
print(mysig)
print("It is a palindrome")
So, find_palindrome(drawer) will give the following output-
drawer
reward
It is a palindrome
However, if I check find_palindrome(post), it will not output anything as tsop is not a valid word. How, can I update the code so that if the word (like post) is not a palindrome, it gives an output-
post
tsop
Not a palindrome
This is a typical use of the else on a loop. See any mid-level tutorial on looping for details.
for word in words:
if mysig == word:
print(myword)
print(mysig)
print("It is a palindrome")
break
else:
print(myword)
print(mysig)
print("It is NOT a palindrome")
Note the careful indentation: else matches the for, not the if
Alternately, you simply set a flag:
is_palindrome = False
for word in words:
if mysig == word:
is_palindrome = True
break
# Do your printing here; test the flag to choose the last line of output.

why can i not use break on this code and what can i use instead? python

The task that I am doing is to develop a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of that word in the list.
sentencelist=[] #variable list for the sentences
word=[] #variable list for the words
positions=[]
words= open("words.txt","w")
position= open("position.txt","w")
question=input("Do you want to enter a sentence? Answers are Y or N.").upper()
if question=="Y":
sentence=input("Please enter a sentance").upper() #sets to uppercase so it's easier to read
sentencetext=sentence.isalpha or sentence.isspace()
while sentencetext==False: #if letters have not been entered
print("Only letters are allowed") #error message
sentence=input("Please enter a sentence").upper() #asks the question again
sentencetext=sentence.isalpha #checks if letters have been entered this time
word = sentence.split(' ')
for (i, check) in enumerate(word): #orders the words
print(sentence)
word = input("What word are you looking for?").upper() #asks what word they want
if (check == word):
positionofword=print("your word is in this position:", i+1)
positionofword=str(positionofword)
else:
print("this didn't work") #print error message
elif question=="N":
print("The program will now close")
else:
print("you did not enter one of the prescribed letters")
words.write(word + " ")
position.write(positionofword + " ")
The problem for me is that I am stuck in the loop of:
word = input("What word are you looking for?").upper() #asks what word they want
if (check == word):
positionofword=print("your word is in this position:", i+1)
positionofword=str(positionofword)
else:
print("this didn't work") #print error message
Which therefore means that I cannot get the words into the file. I have tried to use break, but that did not work out for me because I could not get the words into the file.
I'm new to this site, but I've been stalking for quite a while. Hopefully this is right, I'm open to hearing criticism if I've worded this wrong.
Your logic in the for loop is incorrect - rather than asking once what the word the user wants to find, you ask that for each word in the sentence, and only match if they enter the word they want when that is the current word being checked. You are also printing the sentence once for each word in the sentence. Restructure it like so:
print(sentence)
sentence_words = sentence.split(' ')
word = input("What word are you looking for?").upper() #asks what word they want
for (i, check) in enumerate(sentence_words): #orders the words
if (check == word):
print("your word is in this position:", i+1)
positionofword=i+1
break
else:
print("This didn't work")

Can't get program to print "not in sentence" when word not in sentence

I have a program that asks for input of a sentence, then asks for a word, and tells you the position of that word:
sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")
for i, word in enumerate(words):
if askedword == word :
print(i+1)
#elif keyword != words :
#print ("this not")
However I cannot get the program to work correctly when I edit it to say that if the input word is not in the sentence, then print "this isn't in the sentence"
Lists are sequences, as such you can use the in operation on them to test for membership in the words list. If inside, find the position inside the sentence with words.index:
sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")
if askedword in words:
print('Position of word: ', words.index(askedword))
else:
print("Word is not in the given sentence.")
With sample input:
enter sentence: hello world
enter word to locate position: world
Position of word: 1
and, a false case:
enter sentence: hello world
enter word to locate position: worldz
Word is not in the given sentence.
If you're looking to check against multiple matches then a list-comprehension with enumerate is the way to go:
r = [i for i, j in enumerate(words, start=1) if j == askedword]
Then check on whether the list is empty or not and print accordingly:
if r:
print("Positions of word:", *r)
else:
print("Word is not in the given sentence.")
Jim's answer—combining a test for askedword in words with a call to words.index(askedword)—is the best and most Pythonic approach in my opinion.
Another variation on the same approach is to use try-except:
try:
print(words.index(askedword) + 1)
except ValueError:
print("word not in sentence")
However, I just thought I'd point out that the structure of the OP code looks like you might have been attempting to adopt the following pattern, which also works:
for i, word in enumerate(words):
if askedword == word :
print(i+1)
break
else: # triggered if the loop runs out without breaking
print ("word not in sentence")
In an unusual twist unavailable in most other programming languages, this else binds to the for loop, not to the if statement (that's right, get your editing hands off my indents). See the python.org documentation here.

How to gather information from user input and apply it elsewhere

Hi I am new to programming and I am trying to write a code that will gather information from the input and determine if it is a valid alphabet.
This is my code so far
words = []
word = input('Character: ')
while word:
if word not in words:
words.append(word)
word = input('Character: ')
print(''.join(words),'is a a valid alphabetical string.')
suppose I choose three letters then the output of my code then pressed enter on the fourth,
the code will be:
Character:a
Character:b
Character:c
Character:
abc is a valid alphabetical string.
I want to add to this code so that when I type in a character that is not
from the alphabet the code will do something like this.
Character:a
Character:b
Character:c
Character:4
4 is not in the alphabet.
This is how I want my program to work
Use str.isalpha()
It is gives only true if all characters in the string are letters.
Example:
>>> 'test'.isalpha()
True
>>> 'test44'.isalpha()
False
>>> 'test test'.isalpha()
False
In your code:
words = []
word = input('Character: ')
while word:
if word.isalpha() and word not in words:
words.append(word)
word = input('Character: ')
print(words,'is a a valid alphabetical string.')
You can use a while loop to collect input, then break out of the loop if either the input is empty (the user hit enter without inputting a character) or if the input is not in the alphabet.
letters = []
while True:
letter = input('Character:')
if letter == '':
if letters:
print('{} is a valid alphabetical string.'.format(''.join(letters)))
else:
print('The input was blank.')
break
elif letter.isalpha():
letters.append(letter)
else:
print('{} is not in the alphabet.'.format(letter))
break
You can try this out :-
words = []
while 1:
word = input('Character: ')
if word != '':
try:
if word.isalpha():
pass
if word not in words:
words.append(word)
except Exception:
print word, " is not in the alphabet"
break
else:
res = (''.join(words) +' is a valid alphabetical string.') if (words != []) else "The input was blank."
print res
break

Categories

Resources