python - Python 中的 Trie 实现
问题描述
我试图让这个实现变得清晰。所以我创建hasChild
了Node
. 但是为什么我会收到这个错误?
“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
解决方案
我将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')
推荐阅读
- data-binding - Xamarin Forms:在活动重新启动时维护选定的选项卡
- arrays - 使用 Typescript 从数组中获取唯一的父元素
- python - 从 docker 容器中获取 sftp 服务器的主机 url
- angularjs - 在授权解决之前加载 AngularJS 模板 URL
- less - LESS:以类似于“嵌套规则”的方式创建变量
- laravel - 在 Laravel 5.8 中调用未定义的方法 Maatwebsite\Excel\Excel::create()
- python-3.x - 当我在 chrome web 驱动程序中加载带有活动登录名和书签等的用户数据 chrome 配置文件时,web 驱动程序 add_experimental_options () 不起作用
- lua - Roblox Studio Lua:使用本地脚本克隆
- sql - 如何从 Pentaho-Kettle 中基于动态选择的 sql 查询中获取结果集?
- ansible - Ansible jinja2 未使用 with_items 连接到列表