给定一个字符串(如“helloyellowallow”),解析给定字符串中的所有有效字符串。(例如:[[地狱,你好,黄色],[低,低]…]
我正在寻找最优化的方式来编写代码。这是我的,但我不确定这是不是最好的办法。在
完全披露-这是一个面试问题
master = []
# Dictionary for us to look up words
def is_word(inputstr):
#returns True/False
def processstring(fstr,secstr,li):
if is_word(fstr):
li.append(fstr)
if len(secstr) == 0:
if len(li) != 0:
master.append(li)
return
processstring(fstr+secstr[0], secstr[1:len(secstr)],li)
def wrapperprocess(inpstr):
li = []
if len(inpstr) == 0:
return
processstring('',inpstr,li)
wrapperprocess(inpstr[1:len(inpstr)])
wrapperprocess('helloyellowellow')
print master
这是个好问题
使用
Wordnet
包在解析给定字符串时,从一些索引开始,并不断地折磨索引值 对于索引上的每一个增量,使用wordnet检查同一个单词的存在,它会告诉你特定的子字符串是否有意义!在
要安装
wordnet
:既然您提到您正在寻找一个有效的算法,并且假设您提前获得了字典(而不仅仅是作为一个可调用的谓词),那么您可以使用Aho–Corasick算法。在
当然,如果输入的文本很短,一个更朴素的算法会更快,以避免字典的“昂贵”预处理。在
另外,python的另一个答案是:这里有一个简单的方法来检查每个子字符串:
要获得独特性,请执行以下操作:
^{pr2}$你可以这样做:
印刷品:
^{pr2}$如果您只是在寻找尚未定义的函数
is_word
,那么可以使用如下方法:作为默认的数据结构,Python集合有一个平均值look-up time of O(1)。你不太可能自己写一些更快的东西。在
相关问题 更多 >
编程相关推荐