@@ -39,6 +39,15 @@ def __init__(self, point_count, directed=False):
3939 """
4040 self .directed = directed
4141 self .edges = [[] for i in range (point_count + 1 )]
42+
43+ def edge_count (self ):
44+ """edge_count(self) -> int
45+ Return the count of the edges in the graph.
46+ """
47+ cnt = sum (len (node ) for node in self .edges )
48+ if not self .directed :
49+ cnt //= 2
50+ return cnt
4251
4352 def to_str (self , ** kwargs ):
4453 """to_str(self, **kwargs) -> str
@@ -260,6 +269,11 @@ def graph(point_count, edge_count, **kwargs):
260269 directed = kwargs .get ("directed" , False )
261270 self_loop = kwargs .get ("self_loop" , True )
262271 repeated_edges = kwargs .get ("repeated_edges" , True )
272+ if not repeated_edges :
273+ max_edge = Graph ._calc_max_edge (point_count , directed , self_loop )
274+ if edge_count > max_edge :
275+ raise Exception ("the number of edges of this kind of graph which has %d vertexes must be less than or equal to %d." % (point_count , max_edge ))
276+
263277 weight_limit = kwargs .get ("weight_limit" , (1 , 1 ))
264278 if not list_like (weight_limit ):
265279 weight_limit = (1 , weight_limit )
@@ -309,6 +323,11 @@ def DAG(point_count, edge_count, **kwargs):
309323 self_loop = kwargs .get ("self_loop" , False ) # DAG default has no loop
310324 repeated_edges = kwargs .get ("repeated_edges" , True )
311325 loop = kwargs .get ("loop" , False )
326+ if not repeated_edges :
327+ max_edge = Graph ._calc_max_edge (point_count , not loop , self_loop )
328+ if edge_count > max_edge :
329+ raise Exception ("the number of edges of this kind of graph which has %d vertexes must be less than or equal to %d." % (point_count , max_edge ))
330+
312331 weight_limit = kwargs .get ("weight_limit" , (1 , 1 ))
313332 if not list_like (weight_limit ):
314333 weight_limit = (1 , weight_limit )
@@ -369,6 +388,11 @@ def UDAG(point_count, edge_count, **kwargs):
369388
370389 self_loop = kwargs .get ("self_loop" , True )
371390 repeated_edges = kwargs .get ("repeated_edges" , True )
391+ if not repeated_edges :
392+ max_edge = Graph ._calc_max_edge (point_count , False , self_loop )
393+ if edge_count > max_edge :
394+ raise Exception ("the number of edges of this kind of graph which has %d vertexes must be less than or equal to %d." % (point_count , max_edge ))
395+
372396 weight_limit = kwargs .get ("weight_limit" , (1 , 1 ))
373397 if not list_like (weight_limit ):
374398 weight_limit = (1 , weight_limit )
@@ -450,3 +474,12 @@ def hack_spfa(point_count, **kwargs):
450474 graph .add_edge (u , v , weight = weight_gen ())
451475
452476 return graph
477+
478+ @staticmethod
479+ def _calc_max_edge (point_count , directed , self_loop ):
480+ max_edge = point_count * (point_count - 1 )
481+ if not directed :
482+ max_edge //= 2
483+ if self_loop :
484+ max_edge += point_count
485+ return max_edge
0 commit comments