isolate.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. """
  2. Functions for identifying isolate (degree zero) nodes.
  3. """
  4. import networkx as nx
  5. __all__ = ["is_isolate", "isolates", "number_of_isolates"]
  6. @nx._dispatch
  7. def is_isolate(G, n):
  8. """Determines whether a node is an isolate.
  9. An *isolate* is a node with no neighbors (that is, with degree
  10. zero). For directed graphs, this means no in-neighbors and no
  11. out-neighbors.
  12. Parameters
  13. ----------
  14. G : NetworkX graph
  15. n : node
  16. A node in `G`.
  17. Returns
  18. -------
  19. is_isolate : bool
  20. True if and only if `n` has no neighbors.
  21. Examples
  22. --------
  23. >>> G = nx.Graph()
  24. >>> G.add_edge(1, 2)
  25. >>> G.add_node(3)
  26. >>> nx.is_isolate(G, 2)
  27. False
  28. >>> nx.is_isolate(G, 3)
  29. True
  30. """
  31. return G.degree(n) == 0
  32. @nx._dispatch
  33. def isolates(G):
  34. """Iterator over isolates in the graph.
  35. An *isolate* is a node with no neighbors (that is, with degree
  36. zero). For directed graphs, this means no in-neighbors and no
  37. out-neighbors.
  38. Parameters
  39. ----------
  40. G : NetworkX graph
  41. Returns
  42. -------
  43. iterator
  44. An iterator over the isolates of `G`.
  45. Examples
  46. --------
  47. To get a list of all isolates of a graph, use the :class:`list`
  48. constructor::
  49. >>> G = nx.Graph()
  50. >>> G.add_edge(1, 2)
  51. >>> G.add_node(3)
  52. >>> list(nx.isolates(G))
  53. [3]
  54. To remove all isolates in the graph, first create a list of the
  55. isolates, then use :meth:`Graph.remove_nodes_from`::
  56. >>> G.remove_nodes_from(list(nx.isolates(G)))
  57. >>> list(G)
  58. [1, 2]
  59. For digraphs, isolates have zero in-degree and zero out_degre::
  60. >>> G = nx.DiGraph([(0, 1), (1, 2)])
  61. >>> G.add_node(3)
  62. >>> list(nx.isolates(G))
  63. [3]
  64. """
  65. return (n for n, d in G.degree() if d == 0)
  66. @nx._dispatch
  67. def number_of_isolates(G):
  68. """Returns the number of isolates in the graph.
  69. An *isolate* is a node with no neighbors (that is, with degree
  70. zero). For directed graphs, this means no in-neighbors and no
  71. out-neighbors.
  72. Parameters
  73. ----------
  74. G : NetworkX graph
  75. Returns
  76. -------
  77. int
  78. The number of degree zero nodes in the graph `G`.
  79. """
  80. # TODO This can be parallelized.
  81. return sum(1 for v in isolates(G))