Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/networkx/algorithms/isolate.py: 75%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

12 statements  

1""" 

2Functions for identifying isolate (degree zero) nodes. 

3""" 

4 

5import networkx as nx 

6 

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

8 

9 

10@nx._dispatchable 

11def is_isolate(G, n): 

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

13 

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

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

16 out-neighbors. 

17 

18 Parameters 

19 ---------- 

20 G : NetworkX graph 

21 

22 n : node 

23 A node in `G`. 

24 

25 Returns 

26 ------- 

27 is_isolate : bool 

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

29 

30 Examples 

31 -------- 

32 >>> G = nx.Graph() 

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

34 >>> G.add_node(3) 

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

36 False 

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

38 True 

39 """ 

40 return G.degree(n) == 0 

41 

42 

43@nx._dispatchable 

44def isolates(G): 

45 """Iterator over isolates in the graph. 

46 

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

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

49 out-neighbors. 

50 

51 Parameters 

52 ---------- 

53 G : NetworkX graph 

54 

55 Returns 

56 ------- 

57 iterator 

58 An iterator over the isolates of `G`. 

59 

60 Examples 

61 -------- 

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

63 constructor:: 

64 

65 >>> G = nx.Graph() 

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

67 >>> G.add_node(3) 

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

69 [3] 

70 

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

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

73 

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

75 >>> list(G) 

76 [1, 2] 

77 

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

79 

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

81 >>> G.add_node(3) 

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

83 [3] 

84 

85 """ 

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

87 

88 

89@nx._dispatchable 

90def number_of_isolates(G): 

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

92 

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

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

95 out-neighbors. 

96 

97 Parameters 

98 ---------- 

99 G : NetworkX graph 

100 

101 Returns 

102 ------- 

103 int 

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

105 

106 """ 

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