![](/img/trans.png)
[英]Python: How to find a letter in a sentence's list of words and return those words in their original case (upper/lower)
[英]how to find words in a sentence that have even reverse of those words in python
我想找到所有在同一个句子中颠倒单词的单词。 然而,我得到的代码只找到了这个词的第一次出现。 在我的句子“i am going to eat ma and tae will go”中,我应该得到 am(ma 是反向词)和eat(tae 是反向词)的输出。 我只得到 am.. 我怎样才能修改这个代码来得到所有包含反向单词的单词,即 am 和eat。
input_str='i am going to eat ma and tae will also go'
word=input_str.split()
def isReverseEqual(s1, s2):
# If both the strings differ in length
if len(s1) != len(s2):
return False
l = len(s1)
for i in range(l):
# In case of any character mismatch
if s1[i] != s2[l-i-1]:
return False
return True
def getWord(str, n):
reverse=[]
# Check every string
for i in range(n-1):
# Pair with every other string
# appearing after the current string
for j in range(i+1, n):
# If first string is equal to the
# reverse of the second string
if (isReverseEqual(str[i], str[j])):
reverse.append(str[i])
return reverse
# No such string exists
return "-1"
print(getWord(word, len(word)))
输出: ['am','eat'] 是预期的。
您可以使用:
words = input_str.split()
s = set()
result = set()
for w in words:
r = w[::-1]
if r in s:
result.add(r)
else:
s.add(w)
list(result)
输出:
['am', 'eat']
这是 O(n) 时间复杂度解决方案,因此您必须首先获取单词并遍历它们,每次您有一个新单词时,您都将他添加到一个集合中,如果集合中已经存在反向,则您要添加结果反转
只需更改“返回反向”行的缩进:
input_str='i am going to eat ma and tae will also go'
word=input_str.split()
def isReverseEqual(s1, s2):
# If both the strings differ in length
if len(s1) != len(s2):
return False
l = len(s1)
for i in range(l):
# In case of any character mismatch
if s1[i] != s2[l-i-1]:
return False
return True
def getWord(str, n):
reverse=[]
# Check every string
for i in range(n-1):
# Pair with every other string
# appearing after the current string
for j in range(i+1, n):
# If first string is equal to the
# reverse of the second string
if (isReverseEqual(str[i], str[j])):
reverse.append(str[i])
if reverse:
return reverse
else: # No such string exists
return "-1"
print(getWord(word, len(word)))
input_str= 'i am going to eat ma and tae will also go'
words_list = input_str.split()
new_words_list = [word[::-1] for word in words_list]
data = []
for i in words_list:
if len(i) > 1 and i in new_words_list:
data.append(i)
输出:
['am', 'eat', 'ma', 'tae']
您的解决方案过于复杂。 例如,函数isReverseEqual
可以写成一行:
def isReverseEqual(s1, s2):
return s1==s2[::-1]
让我们简化一下。 首先,把你的句子当作一个集合,而不是一个列表,因为集合查找效率更高:
words = set(input_str.split())
接下来,如果它们的反向副本也在集合/列表中并且它们按字母顺序小于反向副本(以避免重复),则从集合/列表中选择单词:
[w for w in words if w[::-1] in words and w < w[::-1]]
#['am', 'eat']
此解决方案也适用于列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.