问题 - 编写一个名为 answer(document, searchTerms) 的函数,它返回包含所有给定搜索词的文档的最短片段。搜索词可以任何顺序出现。
Inputs:
(string) document = "many google employees can program"
(string list) searchTerms = ["google", "program"]
Output:
(string) "google employees can program"
Inputs:
(string) document = "a b c d a"
(string list) searchTerms = ["a", "c", "d"]
Output:
(string) "c d a"
我下面的程序给出了正确的答案,但时间复杂度非常高,因为我正在做笛卡尔积。如果输入非常高,那么我无法清除这些测试用例。我无法降低这个程序的复杂性,任何帮助将不胜感激。谢谢
import itertools
import sys
def answer(document, searchTerms):
min = sys.maxint
matchedString = ""
stringList = document.split(" ")
d = dict()
for j in range(len(searchTerms)):
for i in range(len(stringList)):
if searchTerms[j] == stringList[i]:
d.setdefault(searchTerms[j], []).append(i)
for element in itertools.product(*d.values()):
sortedList = sorted(list(element))
differenceList = [t - s for s, t in zip(sortedList, sortedList[1:])]
if min > sum(differenceList):
min = sum(differenceList)
sortedElement = sortedList
if sum(differenceList) == len(sortedElement) - 1:
break
try:
for i in range(sortedElement[0], sortedElement[len(sortedElement)-1]+1):
matchedString += "".join(stringList[i]) + " "
except:
pass
return matchedString
如果有人想克隆我的程序,这里是代码