猿问

我收到 File SyntaxError: invalid syntax for line 13

我正在编写代码将单词插入到 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


HUX布斯
浏览 111回答 2
2回答

一只萌萌小番薯

当我从您的代码中复制以下行时self = self.trieDict[word[0]]无法识别的符号位于self导致语法错误的第二个符号的前面。(似乎是 Unicode 0013)只需将其删除或在新行上重写该行并删除有问题的行即可。顺便说一句,self在方法中分配给通常不是一个好主意,因为它指向正在执行该方法的实例。虽然语法上没有错误,但肯定会给读者带来困惑。

大话西游666

这是更正后的代码(用于将节点插入到 trie 中并在 trie 中搜索节点: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.isCompletedef 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()
随时随地看视频慕课网APP

相关分类

Python
我要回答