Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/networkx/algorithms/isolate.py: 73%

11 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-10-20 07:00 +0000

1""" 

2Functions for identifying isolate (degree zero) nodes. 

3""" 

4import networkx as nx 

5 

6__all__ = ["is_isolate", "isolates", "number_of_isolates"] 

7 

8 

9@nx._dispatch 

10def is_isolate(G, n): 

11 """Determines whether a node is an isolate. 

12 

13 An *isolate* is a node with no neighbors (that is, with degree 

14 zero). For directed graphs, this means no in-neighbors and no 

15 out-neighbors. 

16 

17 Parameters 

18 ---------- 

19 G : NetworkX graph 

20 

21 n : node 

22 A node in `G`. 

23 

24 Returns 

25 ------- 

26 is_isolate : bool 

27 True if and only if `n` has no neighbors. 

28 

29 Examples 

30 -------- 

31 >>> G = nx.Graph() 

32 >>> G.add_edge(1, 2) 

33 >>> G.add_node(3) 

34 >>> nx.is_isolate(G, 2) 

35 False 

36 >>> nx.is_isolate(G, 3) 

37 True 

38 """ 

39 return G.degree(n) == 0 

40 

41 

42@nx._dispatch 

43def isolates(G): 

44 """Iterator over isolates in the graph. 

45 

46 An *isolate* is a node with no neighbors (that is, with degree 

47 zero). For directed graphs, this means no in-neighbors and no 

48 out-neighbors. 

49 

50 Parameters 

51 ---------- 

52 G : NetworkX graph 

53 

54 Returns 

55 ------- 

56 iterator 

57 An iterator over the isolates of `G`. 

58 

59 Examples 

60 -------- 

61 To get a list of all isolates of a graph, use the :class:`list` 

62 constructor:: 

63 

64 >>> G = nx.Graph() 

65 >>> G.add_edge(1, 2) 

66 >>> G.add_node(3) 

67 >>> list(nx.isolates(G)) 

68 [3] 

69 

70 To remove all isolates in the graph, first create a list of the 

71 isolates, then use :meth:`Graph.remove_nodes_from`:: 

72 

73 >>> G.remove_nodes_from(list(nx.isolates(G))) 

74 >>> list(G) 

75 [1, 2] 

76 

77 For digraphs, isolates have zero in-degree and zero out_degre:: 

78 

79 >>> G = nx.DiGraph([(0, 1), (1, 2)]) 

80 >>> G.add_node(3) 

81 >>> list(nx.isolates(G)) 

82 [3] 

83 

84 """ 

85 return (n for n, d in G.degree() if d == 0) 

86 

87 

88@nx._dispatch 

89def number_of_isolates(G): 

90 """Returns the number of isolates in the graph. 

91 

92 An *isolate* is a node with no neighbors (that is, with degree 

93 zero). For directed graphs, this means no in-neighbors and no 

94 out-neighbors. 

95 

96 Parameters 

97 ---------- 

98 G : NetworkX graph 

99 

100 Returns 

101 ------- 

102 int 

103 The number of degree zero nodes in the graph `G`. 

104 

105 """ 

106 # TODO This can be parallelized. 

107 return sum(1 for v in isolates(G))