use*_*012 6 python string-matching
给定一个字符串,例如'helloyellowellow',解析给定字符串中的所有有效字符串.(例如:[[地狱,你好,黄色],[低,低] ........]
我正在寻找最优化的编写代码的方法.这是我的,但我不确定这是不是最好的方法.
完全披露 - 这是一个面试问题
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
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
tgt='helloyellowellow'
with open('/usr/share/dict/words') as f:
for word in f:
word=word.strip()
if word in tgt and len(word)>1:
print word
Run Code Online (Sandbox Code Playgroud)
印刷:
el
ell
he
hell
hello
lo
low
loy
ow
owe
we
well
ye
yell
yellow
Run Code Online (Sandbox Code Playgroud)
如果您只是寻找is_word未定义的函数,您可以使用如下方法:
def is_word(word, dic='/usr/share/dict/words'):
if not hasattr(is_word, 'words'):
with open(dic) as f:
is_word.words={word.strip() for word in f}
return word in is_word.words and len(word)>1
Run Code Online (Sandbox Code Playgroud)
作为默认数据结构,Python 集的平均查找时间为 O(1)。你不太可能自己写出更快的东西。
| 归档时间: |
|
| 查看次数: |
626 次 |
| 最近记录: |