我有problem
样本数据集:顶点数为5,边数为4的图,2 2,3 3,4 2,3 4是边列表。
此数据集的度数数组为1 3 2 2 0(按顶点顺序排列)。
我为这个数据集做了双度数组。这是3 3 5 2 0。
我哪里错了?
答案 0 :(得分:0)
#!/usr/bin/env python
from os.path import dirname
with open(dirname(__file__) + '/data/rosalind_ddeg.txt') as input_data:
count_vertices={}
total_number_of_vertices=map(int, input_data.readline().strip().split())[0]
for line in input_data:
vertex_pair=[int(i) for i in line.strip().split()]
if count_vertices.get(vertex_pair[0])==None:
count_vertices[vertex_pair[0]]=[vertex_pair[1]]
else:
count_vertices[vertex_pair[0]]+=[vertex_pair[1]]
if count_vertices.get(vertex_pair[1])==None:
count_vertices[vertex_pair[1]]=[vertex_pair[0]]
else:
count_vertices[vertex_pair[1]]+=[vertex_pair[0]]
for vertex in xrange(1,total_number_of_vertices+1):
total_sum=0
if count_vertices.get(vertex)==None:
print total_sum,
continue
for neighbor in count_vertices[vertex]:
total_sum+=len(count_vertices[neighbor])
print total_sum,
答案 1 :(得分:0)
INFILE = 'rosalind_ddeg.txt'
try:
with open(INFILE) as data:
'''
read data in edgelist format:
1st line: number of vertices, number of edges
subsequent lines:
edge given by two vertices
'''
nvertices, nedges = map(int, data.readline().rstrip().split())
edges = [map(int, line.rstrip().split()) for line in data]
# adjacency dict with vertices as keys,
# lists of adjacent vertices as values
adj = {k:[] for k in range(1,nvertices+1)}
for v1, v2 in edges:
adj[v1].append(v2)
adj[v2].append(v1)
# degree of a vertex is the number of edges that connect to it
# BUT double degree of a vertex is the number of edges that are
# connected to ADJACENT vertices
ddeg = {k:0 for k in adj.keys()}
for vert in adj:
for n in adj[vert]:
ddeg[vert] += len(adj[n])
for k, v in sorted(ddeg.items()):
print v,
except IOError as e:
print('Operation failed: %s' % e.strerror)