问题描述
我正在编写代码,将单词插入到trie数据结构中,然后搜索单词。我的行self = self.trieDict [word [0]](插入函数的第三行)收到无效的语法错误
#Trie data structure
class TrieNode():
trieDict = {}
isComplete = False
def __init__(self,dic,isComplete):
self.trieDict = dic
self.isComplete = isComplete
#self is the root node
def insert(self,word):
while len(word) != 0 and self is not None:
if word[0] in self.trieDict:
self = self.trieDict[word[0]]
word = word[1:]
else:
child = self.TrieNode({},False)
self.trieDict[word[0]] = child
self = child
word = word[1:]
self.isComplete = True
def search(self,word):
while len(word) != 0 and self is not None:
if word[0] in self.trieDict:
word = word[1:]
self = self.trieDict[word[0]]
else:
return False
return self.isComplete
解决方法
当我从您的代码中复制以下行
user_data = '''
#!/bin/bash
echo 'test' > /home/ec2-user/test.txt
'''
第二个self = self.trieDict[word[0]]
的前面正出现无法识别的符号,这会导致语法错误。 (似乎是Unicode 0013)只需将其删除或在新行上重写该行并删除有问题的行即可。
在旁注中,在方法中分配给self
通常不是一个好主意,因为它指向您要在其上执行该方法的实例。虽然在语法上不是不正确的,但肯定会引起读者的困惑。
这是校正后的代码(用于将节点插入特里并在特里中搜索节点:
class TrieNode():
trieDict = {}
isComplete = False
def __init__(self,dic,isComplete):
self.trieDict = dic
self.isComplete = isComplete
#self is the root node
def insert(self,word):
current = self
while len(word) != 0 and current is not None:
if word[0] in current.trieDict:
current = current.trieDict[word[0]]
word = word[1:]
else:
child = TrieNode({},False)
current.trieDict[word[0]] = child
current = child
word = word[1:]
current.isComplete = True
def search(self,word):
current = self
while len(word) != 0 and current is not None:
if word[0] in current.trieDict:
current = current.trieDict[word[0]]
word = word[1:]
else:
return False
return current.isComplete
def test():
node = TrieNode({},False)
node.insert('cat')
node.insert('car')
node.insert('pod')
print(node.search('car'))
print(node.search('ccar'))
print(node.search('pod'))
print(node.search('pode'))
test()