为了账号安全,请及时绑定邮箱和手机立即绑定

我收到 File SyntaxError: invalid syntax for line 13

我收到 File SyntaxError: invalid syntax for line 13

HUX布斯 2023-10-31 21:40:31
我正在编写代码将单词插入到 trie 数据结构中,然后搜索单词。我收到行 self = self.trieDict[word[0]] 无效的语法错误(插入函数中的第三行)#Trie data structureclass 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
查看完整描述

2 回答

?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

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

self = self.trieDict[word[0]]

无法识别的符号位于self导致语法错误的第二个符号的前面。(似乎是 Unicode 0013)只需将其删除或在新行上重写该行并删除有问题的行即可。

顺便说一句,self在方法中分配给通常不是一个好主意,因为它指向正在执行该方法的实例。虽然语法上没有错误,但肯定会给读者带来困惑。


查看完整回答
反对 回复 2023-10-31
?
大话西游666

TA贡献1817条经验 获得超14个赞

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


查看完整回答
反对 回复 2023-10-31
  • 2 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信