栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

给定一个(父,子)的平面列表,创建一个分层的字典树[关闭]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

给定一个(父,子)的平面列表,创建一个分层的字典树[关闭]

假设它的行为良好(没有循环,没有重复的名称或一个孩子有多个父母),您可以简单地使用“有向图”并遍历它。为了找到根,我还使用了一个包含布尔值的字典,该布尔值指示该名称是否存在任何父项:

lst = [('john','marry'), ('mike','john'), ('mike','hellen'), ('john','elisa')]# Build a directed graph and a list of all names that have no parentgraph = {name: set() for tup in lst for name in tup}has_parent = {name: False for tup in lst for name in tup}for parent, child in lst:    graph[parent].add(child)    has_parent[child] = True# All names that have absolutely no parent:roots = [name for name, parents in has_parent.items() if not parents]# traversal of the graph (doesn't care about duplicates and cycles)def traverse(hierarchy, graph, names):    for name in names:        hierarchy[name] = traverse({}, graph, graph[name])    return hierarchytraverse({}, graph, roots)# {'mike': {'hellen': {}, 'john': {'elisa': {}, 'marry': {}}}}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611751.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号