1

問題があります

サンプル データセット: 頂点の数が 5、エッジの数が 4 で、1 2、2 3、4 3、2 4 がエッジ リストであるグラフ。

このデータセットの次数配列は 1 3 2 2 0 (頂点順) です。

このデータセットに対して 2 次配列を作成しました。3 3 5 2 0 です。

どこが間違っていますか?

4

2 に答える 2

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)
于 2014-08-05T22:10:27.387 に答える
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,
于 2014-08-05T21:40:24.607 に答える