找到无向图的程度

时间:2014-03-16 14:37:10

标签: python

我试图找到无向图的度分布。我尝试了以下代码:

graph = { "a" : ["c"],
          "b" : ["c", "e"],
          "c" : ["a", "b", "d", "e"],
          "d" : ["c"],
          "e" : ["c", "b"],
          "f" : []
        }

def generate_edges(graph):
    edges = []
    for node in graph:
        for neighbour in graph[node]:
            edges.append((node, neighbour))

    return edges

print(generate_edges(graph))

我的输出是这样的:

[('c', 'a'), ('c', 'b'), ('c', 'd'), ('c', 'e'), ('b', 'c'), ('b', 'e'), ('a', 'c'), ('e', 'c'), ('e', 'b'), ('d', 'c')]

我想找到学位,但我没有得到它。我需要输出为[1,2,2,0,1]这是一个列表,其中索引值的范围从0到最大程度(即上图4中“c”的最大程度)并且索引值是度数等于该索引的节点数。 (在上面的图中,有1个节点0度,2个1度,2个2度,3个没有,最后1个4度)。因此[1,2,2,0,4]。没有人使用NetworkX,有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

graph = { "a" : ["c"],
          "b" : ["c", "e"],
          "c" : ["a", "b", "d", "e"],
          "d" : ["c"],
          "e" : ["c", "b"],
          "f" : [] }

def max_length(x):
    return len(graph[x])

# Determine what index has the longest value
index = max(graph, key=max_length)
m = len(graph[index])

# Fill the list with `m` zeroes
out = [0 for x in range(m+1)]

for k in graph:
    l = len(graph[k])
    out[l]+=1

print(out)

输出[1, 2, 2, 0, 1]

答案 1 :(得分:1)

使用Counter的另一种解决方案:

from collections import Counter
a = Counter(map(len, graph.values())) # map with degree as key and number of nodes as value
out = [a[i] for i in range(max(a)+1)] # transform the map to a list

答案 2 :(得分:0)

您可以通过简单地查找每个元素列表的长度来找到各个节点的度数。

all_degrees = map(len, graph.values())

在您的情况下,这会产生单独的度数,不一定与元素的顺序相同。

[1, 4, 2, 2, 1, 0]

接下来就是列表中的频率计数。

from collections import defaultdict
freq = defaultdict(int)
for i in all_degrees:
    freq[i] += 1
print freq
Out: defaultdict(<type 'int'>, {0: 1, 1: 2, 2: 2, 4: 1})

正如预期的那样,freq现在会给出您可以打印的每个值的计数,附加到列表等。您只需打印字典freq的值为

print freq.values()

返回所需的列表[1, 2, 2, 0, 1]。或者您可以创建一个空列表并将值附加到

out = list()
for i in range(max(all_degrees)+1):
   out.append(freq[i])

再次返回out = [1,2,2,0,1] - 所需的输出。