简体   繁体   English

判断图是有向还是无向

[英]Determine if the graph is directed or undirected

Can anyone offer some suggestions on how to write a method that returns if a graph is directed or undirected in python?如果 python 中的图是有向的或无向的,任何人都可以提供一些关于如何编写返回的方法的建议吗?

Thanks.谢谢。


class DiGraph :
    def __init__ ( self ) :
        self._adj = {}
        
    def add_node ( self , u ) :
        if u not in self._adj :
            self._adj [ u ] = []
            
    def add_edge ( self , u , v , weight =1) :
        self.add_node ( u )
        self.add_node ( v )
        self._adj [ u ].append (( v , weight ) )

I'm not sure if this is what you are looking for but here is how I though about it.我不确定这是否是您正在寻找的,但这是我的想法。

some_graph = DiGraph()
some_graph.add_edge("a","b")
some_graph.is_directed()

This returns True since there is only an edge in one direction.这将返回 True,因为在一个方向上只有一条边。

some_graph = DiGraph()
some_graph.add_edge("a","b")
some_graph.add_edge("b","a")
some_graph.is_directed()

This returns False since there are edges in both directions with the same weight.这将返回 False,因为在两个方向上都有具有相同权重的边。

some_graph = DiGraph()
some_graph.add_edge("a","b")
some_graph.add_edge("b","a",2)
some_graph.is_directed()

This returns True since even though there are edges in both directions they have different weights.这将返回 True,因为即使在两个方向上都有边,它们也具有不同的权重。

Full code:完整代码:

class DiGraph :
    def __init__ ( self ) :
        self._adj = {}
        
    def add_node ( self , u ) :
        if u not in self._adj :
            self._adj [ u ] = []
            
    def add_edge ( self , u , v , weight =1) :
        self.add_node ( u )
        self.add_node ( v )
        self._adj [ u ].append (( v , weight ) )

    def is_directed ( self ) :
        for u, neigh in self._adj.items():
            for n in neigh:
                print("u", u, "neigh:", neigh)
                if n[0] != u and not ([(node,w) for node,w in self._adj[n[0]] if (node==u and w==n[1])]):
                    return True
        return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM