我正在获取文件语法错误:第13行self=self.trieDict[word[0]的语法无效

2024-09-30 01:24:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: andselffalsechildlenisdefnot
2条回答

以下是更正后的代码(用于将节点插入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.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()

当我从您的代码中复制以下行时

self = self.trieDict[word[0]]

导致语法错误的第二个self前面有一个无法识别的符号。(似乎是Unicode 0013)只需删除它或在新行上重写该行,然后删除有问题的行

另一方面,在方法中分配给self通常不是一个好主意,因为它指向您正在执行该方法的实例。虽然在语法上不是不正确的,但它肯定会给读者带来困惑

相关问题 更多 >

    热门问题