Python 中的 Trie 实现

Trie implementation in Python

我试图让这个实现变得清晰。所以我创建了 NodehasChild 函数。但是为什么我会收到这个错误?

'NoneType' object has no attribute 'hasChild'

class Node():
    def __init__(self,word):
        self.value = str(word)
        self.children = {}   
        self.isEndOfWord = False

    def hasChild(self,ch):
        return ch in self.children.keys()

    def addChild(self,ch):
        nodenew = Node(str(ch))
        self.children[ch] = nodenew

    def getChild(self,ch):
        return self.children.get(ch)

class Trie():
    def __init__(self):
        self.root = Node('')

    def insert(self,children):
        current = self.root
        for ch in children:
            if (current.hasChild(ch) is False):
                current.addChild(ch)
            current = self.root.getChild(ch)
        current.isEndOfWord = True

我将 current.hasChild(ch) is False 更改为 not current.hasChild(ch) and current = self.root.getChild(ch) into current = current.getChild(ch) 的插入函数。有用。非常感谢!

class Node():
def __init__(self,word):
    self.value = str(word)
    self.children = {}   
    self.isEndOfWord = False

def hasChild(self,ch):
    return ch in self.children.keys()

def addChild(self,ch):
    nodenew = Node(ch)
    self.children[ch] = nodenew

def getChild(self,ch):
    return self.children.get(ch)

class Trie():
def __init__(self):
    self.root = Node('')

def insert(self,children):
    current = self.root
    for ch in children:
        if (not current.hasChild(ch)):
            current.addChild(ch)
        current = current.getChild(ch)
    current.isEndOfWord = True

trie = Trie()
trie.insert('cat')
trie.insert('can')