Reputation: 1
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.
Upvotes: 1
Views: 807
Reputation: 2231
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
Upvotes: 1
Reputation: 586
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) )
Upvotes: 0