亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我收到 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 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號