我正在编写代码,将单词插入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
以下是更正后的代码(用于将节点插入trie并在trie中搜索节点):
当我从您的代码中复制以下行时
self = self.trieDict[word[0]]
导致语法错误的第二个
self
前面有一个无法识别的符号。(似乎是Unicode 0013)只需删除它或在新行上重写该行,然后删除有问题的行另一方面,在方法中分配给
self
通常不是一个好主意,因为它指向您正在执行该方法的实例。虽然在语法上不是不正确的,但它肯定会给读者带来困惑相关问题 更多 >
编程相关推荐