首页 > 解决方案 > Python 中的 Trie 实现

问题描述

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

“NoneType”对象没有属性“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

标签: pythontrie

解决方案


我将current.hasChild(ch) is False更改为not current.hasChild(ch)current = self.root.getChild(ch) 更改为插入函数的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')

推荐阅读