获取邻接表中的所有叶子
Get all leafs in an adjacency list
给定如下结构:
graph = {
# c1 is root node, graph is directed, c1 is source/root node
'c1': ['c2', 'c3'],
'c2': ['c4']
}
c1
/\
/ \
c2 c3
/
/
c4
找到图中所有叶子的通用算法是什么?我的第一个想法是:
# values in the 'from' section, that don't have a 'to' entry
set(itertools.chain(*graph.values())) - set(graph.keys())
# {'c3', 'c4'}
这是正确的做法吗?还有哪些其他方法可以确定某物是否是一片叶子?
您可以简化您的作品以使其更有效率:
leaves = set()
leaves.update(*graph.values())
leaves -= graph.keys()
给定如下结构:
graph = {
# c1 is root node, graph is directed, c1 is source/root node
'c1': ['c2', 'c3'],
'c2': ['c4']
}
c1
/\
/ \
c2 c3
/
/
c4
找到图中所有叶子的通用算法是什么?我的第一个想法是:
# values in the 'from' section, that don't have a 'to' entry
set(itertools.chain(*graph.values())) - set(graph.keys())
# {'c3', 'c4'}
这是正确的做法吗?还有哪些其他方法可以确定某物是否是一片叶子?
您可以简化您的作品以使其更有效率:
leaves = set()
leaves.update(*graph.values())
leaves -= graph.keys()