Python 中的关系图

Relationship graph in Python

我想在给定关系图的情况下计算每个人的朋友数 而不使用任何库。该图表示为列表的列表:

graph = [[A,B],[A,C],[C,B],[B,D],[E]]

预期字典输出:{'A':2, 'B':3, 'C':2, 'D':1, 'E':0}

注意:由于E没有朋友,所以E应该是0

所以你可以这样做

    graph = [["A","B"],["A","C"],["C","B"],["B","D"],["E"]]
    ans = {}
    for n in graph:
        if len(n) == 1:
                ans[n[0]] = ans.get(n[0], 0)
        else:
                l, r = n
                ans[l] = ans.get(l, 0) + 1
                ans[r] = ans.get(r, 0) + 1

    print(ans)
    # {'A': 2, 'B': 3, 'C': 2, 'D': 1, 'E': 0}

您可以使用名为 NetworkX 的特定于图的 python 库。我更改了数据以便于加载。

import networkx as nx
graph = [['A','B'],['A','C'],['C','B'],['B','D']]

G = nx.Graph()
G.add_edges_from(graph)
G.add_node('E')

dict(G.degree)                                                         
#  {'A': 2, 'B': 3, 'C': 2, 'D': 1, 'E': 0}

编辑:此答案是在添加 "without using any libraries" 警告之前给出的。

得到解决方案。有更好的方法吗?

graph = [['A','B'],['A','C'],['C','B'],['B','D'],['E']]
dct ={}
for v in graph:
    for x in v:
            if x in v:
                    if x in dct.keys():
                            dct[x] += 1
                    else:
                            dct[x]= len(v)-1

print(dct)
{'A': 2, 'B': 3, 'C': 2, 'D': 1, 'E': 0}

无需更改输入格式的直接解决方案

>>> graph = [['A', 'B'], ['A', 'C'],['C', 'B'], ['B', 'D'], ['E']]
>>> from collections import defaultdict
>>> friends_counter = defaultdict(int)
>>> for friends in graph:
...     for person in friends:
...         friends_counter[person] += len(friends) - 1
>>> dict(friends_counter)
{'A': 2, 'B': 3, 'C': 2, 'D': 1, 'E': 0}