Add palindrome count

Question:

So I have a code that counts the amount of words
But I need it to count palindrome words times instead of one

For example, "Kids love doing gag. Gag is good."

We first enter how many words we will look for

We write 2

Then one by one we write these words

F.e first one is kids, and the second is gag.

As a result, our answer should be 5 (1 time kids, 2 times gag (But this is a palindrome, so it counts
4 times)

This is the code

text = input("Enter:")
text = text.lower()


quantity = int(input("How Many Words Do You Want Find: "))
word_counter = 0
word_for_find = []
for i in text:
    if i == "." or i == "," or i == "!" or i == "?":
        text = text.replace(i, "")

lst_text = text.split()

for i in range(quantity):
    temp = input("Enter The Word: ")
    temp = temp.lower()
    word_for_find.append(temp)

for i in lst_text:
    for j in word_for_find:
        if j == i:
            word_counter += 1


print(word_counter)
Asked By: Gabe Newal

||

Answers:

If I’m understanding you correctly you want to count palindromes twice. To check that I would create an if statement in the other if statement checking if it’s the same in reverse:

if i == i[::-1]:
   word_counter += 2
else:
   word_counter += 1
Answered By: Andreas Sabelfeld

Your code has many flaws, you use a lot of loops for tasks that should be handled in a more simpler way (for instance the nested loops over all characters, and all punctuation combined with str.replace is inefficient).

For a pythonic solution, I would use re.findall and collections.Counter:

import re
from collections import Counter

text = "Kids love doing gag. Gag is good."

# extract lowercase words and count them
c = Counter(re.findall(r'w+', text.lower()))

# for each key
for k in c:
    # check if this is a palindrome
    if k == k[::-1]:
        # and multiply the count by 2
        c[k] *= 2
        
print(dict(c))

Output:

{'kids': 1, 'love': 1, 'doing': 1, 'gag': 4, 'is': 1, 'good': 1}
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.