vertice = input("enter the vertices: ")
vertice = [x.strip(' ') for x in vertice.split(',')]
edge = input("enter the edges: ")
edge = [x.strip(' ') for x in edge.split(',')]
print("Number of vertices: ", len(vertice))
print("Number of edges: ", len(edge)
从这里我试图找到一个输入的度数序列,如: a,b,c表示顶点 和边缘的a-b,b-c,c-a。如何使用此类输入执行此操作? 寻找像[2,2,2]
这样的输出答案 0 :(得分:1)
您可以使用Counter
计算与每个顶点关联的边:
>>> from collections import Counter
>>> vertices = ['a', 'b', 'c', 'd']
>>> edges = ['a-b', 'a-c', 'b-c', 'd-a']
>>> degree = Counter(vertex for edge in edges for vertex in edge.split('-'))
>>> [degree[vertex] for vertex in vertices]
[3, 2, 2, 1]
在上面的Counter
构造函数中,接受一个可迭代的项目,并返回一个dict
类似对象,其中唯一项是键,并为相应的计数值。
>>> items = list(vertex for edge in edges for vertex in edge.split('-'))
>>> items
['a', 'b', 'a', 'c', 'b', 'c', 'd', 'a']
>>> degree = Counter(items)
>>> degree
Counter({'a': 3, 'c': 2, 'b': 2, 'd': 1})
由于Counter
的排序是随机的,我们需要使用列表推导来迭代顶点,以便以相同的顺序生成度数列表。
>>> [degree[vertex] for vertex in vertices]
[3, 2, 2, 1]
答案 1 :(得分:0)
您始终可以使用networkx软件包 - 它可以为您提供大多数(如果不是全部)操作图形的功能。假设您有一个径向连接的4个节点的路径,您会发现这样的程度:
from networkx import nx
G = nx.Graph()
G.add_path([0,1,2,3])
deg=G.degree(G.nodes()).values()
print("number of vertices: ",G.number_of_nodes())
print("number of edges: ",G.number_of_edges())
print("degree list: ",sorted(deg))
>>number of vertices: 4
>>number of edges: 3
>>degree list: [1, 1, 2, 2]