[英]Why am I getting: SyntaxError: invalid syntax (<string>, line 1) in python?
[英]I am getting File SyntaxError: invalid syntax for line 13 self = self.trieDict[word[0]]
我正在編寫代碼將單詞插入到特里數據結構中,然后搜索單詞。 我收到 line self = ?self.trieDict[word[0]] 的無效語法錯誤(插入函數中的第 3 行)
#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
當我從您的代碼中復制以下行時
self = self.trieDict[word[0]]
一個無法識別的符號就在導致您的語法錯誤的第二個self
。 (似乎是 Unicode 0013)只需將其刪除或在新行上重寫該行並刪除違規行。
在旁注中,在方法中分配給self
通常不是一個好主意,因為它指向您正在執行該方法的實例。 雖然在語法上沒有錯誤,但它肯定會引起讀者的混淆。
這是更正后的代碼(用於將節點插入到特里並在特里中搜索節點:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.