【发布时间】:2020-06-23 03:37:06
【问题描述】:
我想在同一个句子中找到所有单词颠倒的单词。 然而,我得到的代码只找到了这个词的第一次出现。 在我的句子“我要吃 ma 和 tae 也会去”中,我应该得到 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'] 是预期的。
【问题讨论】:
-
在我看来,这项活动在技术上无法 100% 正确完成。如果你输入单词“deal”但你真的想要单词“lead”会发生什么。
-
您期待的是
['am','eat']而不是['ma', 'tea'],因为am和eat出现在句子的首位?或者预期输出的顺序无关紧要?
标签: python