当我执行此代码时,它会打印' Constructed',这意味着它执行了Trie Construction - 然后我的终端输出什么,它没有返回或打印任何错误,它只是空白,好像它还在解决这个问题。 while循环有问题吗?这是' trie'是一个外部变量?
class node:
def __init__(self, parent, daughters, edge):
self.parent = parent
self.daughters = daughters
self.edge = edge
trie.append(self)
self.index = len(trie) - 1
是节点列表,是我定义的类。
patterns
def TrieConstruction(patterns, trie):
trie.append(node(0, [], 0))
for pattern in patterns:
currentNode = trie[0]
for base in pattern:
for daughter in currentNode.daughters:
if base == daughter.edge:
currentNode = daughter
break
else:
trie.append(node(currentNode, [], base))
currentNode = trie[-1]
print('Constructed.')
return
def PrefixTrieMatching(text, trie):
v = trie[0]
for index, base in enumerate(text):
if v.daughters == []:
pattern_out = []
climb(v.index)
return ''.join(pattern_out)
else:
for daughter in v.daughters:
if base == daughter.edge:
v = daughter
break
else:
print('No matches found.')
return
def climb(index):
if index == 0:
return
else:
pattern_out.append(node.edge)
climb(trie[index].parent)
def TrieMatching(text, trie):
while text != []:
PrefixTrieMatching(text, trie)
text = text[0:len(text) - 2]
print('Complete.')
return
是固定字符串列表。
print('Next, we generate a trie with the patterns, and then run the text over the trie to search for matches.')
trie = []
TrieConstruction(patterns, trie)
TrieMatching(text, trie)
gsutil ls gs://your-bucket/a* > a.out &
gsutil ls gs://your-bucket/b* > b.out &
...
gsutil ls gs://your-bucket/b* > z.out &
wait
cat ?.out > listing.out
答案 0 :(得分:1)
编辑:
忽略我之前的回答,如果您输入的字符串为text
,则应为:
while text != "":
PrefixTrieMatching(text, trie)
text = text[0:len(text) - 2]
因为string
永远不会是空列表
答案 1 :(得分:1)
你正在做的工作超过了所需的工作,只需使用while text
,它只返回False
一个空字符串,然后将你的字符串切片,一次从末尾切两个字符:
def TrieMatching(text, trie):
while text:
PrefixTrieMatching(text, trie)
text = text[:-2]
空列表,str,dict等将始终评估为False,因此您无需明确检查if my_list != []
,if my_str != ""
,if my_list
和if my_str
等.. 足够了。