简体   繁体   中英

How to compare reverse strings in list of strings with the original list of strings in python?

Input a given string and check if any word in that string matches with its reverse in the same string then print that word else print $

I split the string and put the words in a list and then I reversed the words in that list. After that, I couldn't able to compare both the lists.

str = input()
x = str.split()
for i in x: # printing i shows the words in the list
    str1 = i[::-1] # printing str1 shows the reverse of words in a new list
    # now how to check if any word of the new list matches to any word of the old list 
    if(i==str):
        print(i)
        break
    else:
        print('$)

Input: suman is a si boy .

Output: is ( since reverse of 'is' is present in the same string)

a = 'suman is a si boy'

# Construct the list of words
words = a.split(' ')

# Construct the list of reversed words
reversed_words = [word[::-1] for word in words]

# Get an intersection of these lists converted to sets
print(set(words) & set(reversed_words))

will print:

{'si', 'is', 'a'}

You almost have it, just need to add another loop to compare each word against each inverted word. Try using the following

str = input()
x = str.split()
for i in x:
    str1 = i[::-1]
    for j in x: # <-- this is the new nested loop you are missing
        if j == str1: # compare each inverted word against each regular word
            if len(str1) > 1: # Potential condition if you would like to not include single letter words
                print(i)

Update

To only print the first occurrence of a match, you could, in the second loop, only check the elements that come after. We can do this by keeping track of the index:

str = input()
x = str.split()
for index, i in enumerate(x):
    str1 = i[::-1]
    for j in x[index+1:]: # <-- only consider words that are ahead
        if j == str1: 
            if len(str1) > 1: 
                print(i)

Note that I used index+1 in order to not consider single word palindromes a match.

Another way to do this is just in a list comprehension:

string = 'suman is a si boy'  

output = [x for x in string.split() if x[::-1] in string.split()]

print(output)

The split on string creates a list split on spaces. Then the word is included only if the reverse is in the string.

Output is:

['is', 'a', 'si']

One note, you have a variable name str . Best not to do that as str is a Python thing and could cause other issues in your code later on.

If you want word more than one letter long then you can do:

string = 'suman is a si boy'

output = [x for x in string.split() if x[::-1] in string.split() and len(x) > 1]

print(output)

this gives:

['is', 'si']

Final Answer...

And for the final thought, in order to get just the 'is' :

string = 'suman is a si boy'

seen = []
output = [x for x in string.split() if x[::-1] not in seen and not seen.append(x) and x[::-1] in string.split() and len(x) > 1]                      

print(output)

output is:

['is']

BUT , this is not necessarily a good way to do it, I don't believe. Basically you are storing information in seen during the list comprehension AND referencing that same list. :)

This answer wouldn't show you 'a' and won't output 'is' with 'si'.

str = input() #get input string
x = str.split() #returns list of words
y = [] #list of words
while len(x) > 0 :
    a = x.pop(0) #removes first item from list and returns it, then assigns it to a
    if a[::-1] in x: #checks if the reversed word is in the list of words
                     #the list doesn't contain that word anymore so 'a' that doesn't show twice wouldn't be returned
                     #and 'is' that is present with 'si' will be evaluated once

        y.append(a)

print(y) # ['is']

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