221k views
1 vote
g Palindrome counting. Write a Python program stored in a file q3.py to calculate the number of occurrences of palindrome words and palindrome numbers in a sentence. Your program is case-insensitive, meaning that uppercase and lowercase of the same word should be considered the same. The program should print the palindromes sorted alphanumerically with their number of occurrences. Numbers must be printed first, and words must be printed nex

User Odedfos
by
3.9k points

1 Answer

4 votes

Answer:

The program is as follows:

sentence = input("Sentence: ")

numbers = []; words = []

for word in sentence.split():

if word.lower() == word[::-1].lower():

if word.isdigit() == False:

words.append(word)

else:

numbers.append(int(word))

words.sort(); numbers.sort()

print(numbers); print(words)

Step-by-step explanation:

This gets input for sentence

sentence = input("Sentence: ")

This initializes two lists; one for numbers, the other for word palindromes

numbers = []; words = []

This iterates through each word of the sentence

for word in sentence.split():

This checks for palindromes

if word.lower() == word[::-1].lower():

If the current element is palindrome;

All word palindromes are added to word palindrome lists

if word.isdigit() == False:

words.append(word)

All number palindromes are added to number palindrome lists

else:

numbers.append(int(word))

This sorts both lists

words.sort(); numbers.sort()

This prints the sorted lists

print(numbers); print(words)

User Qwe
by
4.1k points