2 回答

TA貢獻1795條經驗 獲得超7個贊
當我從您的代碼中復制以下行時
self = self.trieDict[word[0]]
無法識別的符號位于self
導致語法錯誤的第二個符號的前面。(似乎是 Unicode 0013)只需將其刪除或在新行上重寫該行并刪除有問題的行即可。
順便說一句,self
在方法中分配給通常不是一個好主意,因為它指向正在執行該方法的實例。雖然語法上沒有錯誤,但肯定會給讀者帶來困惑。

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()
添加回答
舉報