Search code examples
pythontrie

I am getting File SyntaxError: invalid syntax for line 13 self = self.trieDict[word[0]]


I am writing code to insert words into a trie data structure and then search the words. I am getting invalid syntax error for line self = self.trieDict[word[0]] (3rd line in the insert function)

#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

Solution

  • When I copied the following line from your code

    self = self.trieDict[word[0]]

    an unrecognized symbol is right in front of the second self that is causing your syntax error. (It seems to be Unicode 0013) Simply delete it or rewrite the line on a new line and remove the offending line.

    On a sidenote, assigning to self in a method is usually not a good idea as it points to the instance on which you are executing the method. While not syntactically incorrect, it will definitely cause confusion to the reader.