简体   繁体   中英

python how many palindromes are in a list of strings

I'm trying to input a sequence of words and count how many palindromes or non-palindromes(unique words) are in the sequence but can't tell what I'm doing wrong. My loop isn't counting the elements of the list and is instead counting the entire list I believe.

user_input = input('Enter word sequence:')

string = user_input.split()

temp = [i[::-1] for i in string]

unique = 0
is_palindrome = 0

for i in temp:

   if i in temp == string:
      is_palindrome += 1

   else:
       unique += 1

print('There are', is_palindrome, 'Palindromes, and', unique, 'unique words')

if someone could help me I'd appreciate it.

You splitted input and reversed every word. You implemented very good so far but below, your implementation is wrong.

for i in temp:

   if i in temp == string:
      is_palindrome += 1

You are going through in temp but this line of code if i in temp == string is not the right implementation because you are comparing if i in temp which returns boolean and string which is a list. You need to compare temp list's indexes and string list's indexes if they match or not. if they match they are palindrome. You can implement as follow.

for i in range(len(temp)):
    if temp[i] == string[i]:
        palindrome += 1
    else:
        unique += 1

Since reading the words does not seem to be the kernel of the question, let us skip this step and declare explicitly a list of words, then count the number of words, that coincide with the reciprocal:

my_words = [ 'abccba', '101101', 'joy', 'bar', 'john', 'anna' ]
print( [ word == word[::-1] for word in my_words ].count(True) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM