Python program to get number of Palindrome words in a line of text
What is Palindrome?
A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward.
Examples:madam,lol,racecar,..etc
Program:
Method 1:
lower():This method converts a string into lowercase
word[::-1]:This is used to reverse lists,strings
Algorithm:
Step1:Take input from user
Step2:Split sentence into words
Step3:Check if word and its reverse are same
Step4:If Same add word to list l
Step5:Total number of palindromes is length of list ll=[]
st=input("enter sentence")
for word in st.split():
if word.lower()==word[::-1].lower():
l.append(word)
print("Total number of palindrome words in a sentence: ",len(l))
Output:
Method 2:
checkP: Function to check if a word is palindrome
countP(str):Function to count palindrome words
Algorithm:
Step1:splitting each word as spaces as delimiter and storing it into a list
Step2:Iterating every element from list and checking if it is a palindrome
Step3:if the word is a palindrome, increment the count.
def checkP(word): #2
if word.lower() == word.lower()[::-1]:
return True
def countP(str):
count = 0
Words = str.split(" ") #1
for elements in Words:
if (checkP(elements)):
count += 1 #3
print(count)
countP(input("enter text"))
Output:
0 Comments
Post a Comment