Python 有没有办法写一篇更好的文章;最高学位;?
我想是的,因为我是Python新手 我收到了一些传递,其中一个是:“给定一个图,找到具有最大次数的节点,并将其返回到列表中。” 我的解决方案:Python 有没有办法写一篇更好的文章;最高学位;?,python,networkx,Python,Networkx,我想是的,因为我是Python新手 我收到了一些传递,其中一个是:“给定一个图,找到具有最大次数的节点,并将其返回到列表中。” 我的解决方案: def max_degree(graph): """ :param graph: non-null and non-oriented networkx type graph to analyze. :return: list of nodes of this graph with maximum degree; 0 if the
def max_degree(graph):
"""
:param graph: non-null and non-oriented networkx type graph to analyze.
:return: list of nodes of this graph with maximum degree; 0 if the graph has no nodes; -1 if the graph is disconnected;
"""
if len(graph.nodes) == 0:
return 0
if not nx.is_connected(graph):
return -1
# node_grade_list -> [(<node>, <grade>), ...]
node_grade_list = sorted(grafo.degree, key=lambda x: x[1], reverse=True)
max_grade = node_grade_list[0][1]
max_grade_nodes_list = []
for node in node_grade_list:
if node[1] == max_grade:
max_grade_nodes_list.append(node[0])
return max_grade_nodes_list
def max_degree(图形):
"""
:param graph:要分析的非null和非定向networkx类型的图形。
:return:此图的最大度节点列表;如果该图没有节点,则为0;如果该图已断开连接,则为-1;
"""
如果len(图节点)==0:
返回0
如果不是nx,是否连接(图表):
返回-1
#节点等级列表->[(,),…]
节点等级列表=排序(grafo.degree,key=lambda x:x[1],reverse=True)
最大等级=节点等级列表[0][1]
最大等级节点列表=[]
对于节点等级列表中的节点:
如果节点[1]==最大坡度:
最大等级节点列表。追加(节点[0])
返回最大等级节点列表
我想问你的是:有没有办法让它更有效率呢?我经常碰头,但我找不到其他更“舒适”的路线。我接受任何代码,谢谢。假设graph.degree是元组列表
[(<node>, <grade>), ...]
这会更快,因为这是O(n),而排序需要O(n*log(n))
修订代码
def max_degree(graph):
"""
:param graph: non-null and non-oriented networkx type graph to analyze.
:return: list of nodes of this graph with maximum degree; 0 if the graph has no nodes; -1 if the graph is disconnected;
"""
if len(graph.nodes) == 0:
return 0
if not nx.is_connected(graph):
return -1
# graph.degree -> [(<node>, <grade>), ...]
max_grade = max(graph.degree, key=lambda x: x[1])[1]
return [node[0] for node in graph.degree if node[1] == max_grade]
这意味着对于1024个元素的列表,n=2^10它将是log(2^10)=10倍快
对于较小的列表,例如n=10,使用哪种方法并不重要。grafo是打字错误(即,你是指图形吗)?是的。在这里发布之前,我不得不把它翻译成英语,因为它是用意大利语写的。你能更好地解释一下“这是因为这是O(n),而排序需要O(n*log(n)),这是什么意思吗?”你的意思是相反的吗?@AlbertoUrsino——补充了更多的解释。让我知道这是否有用。哎哟,我没有看到n*log(n),我想你写了O(log(n)),这就是为什么我怀疑。。。顺便说一下,非常感谢你的解释。
def max_degree(graph):
"""
:param graph: non-null and non-oriented networkx type graph to analyze.
:return: list of nodes of this graph with maximum degree; 0 if the graph has no nodes; -1 if the graph is disconnected;
"""
if len(graph.nodes) == 0:
return 0
if not nx.is_connected(graph):
return -1
# graph.degree -> [(<node>, <grade>), ...]
max_grade = max(graph.degree, key=lambda x: x[1])[1]
return [node[0] for node in graph.degree if node[1] == max_grade]
O(n*log(n))/log(n) = O(log(n)).