community_utils.py 867 B

123456789101112131415161718192021222324252627
  1. """Helper functions for community-finding algorithms."""
  2. __all__ = ["is_partition"]
  3. def is_partition(G, communities):
  4. """Returns *True* if `communities` is a partition of the nodes of `G`.
  5. A partition of a universe set is a family of pairwise disjoint sets
  6. whose union is the entire universe set.
  7. Parameters
  8. ----------
  9. G : NetworkX graph.
  10. communities : list or iterable of sets of nodes
  11. If not a list, the iterable is converted internally to a list.
  12. If it is an iterator it is exhausted.
  13. """
  14. # Alternate implementation:
  15. # return all(sum(1 if v in c else 0 for c in communities) == 1 for v in G)
  16. if not isinstance(communities, list):
  17. communities = list(communities)
  18. nodes = {n for c in communities for n in c if n in G}
  19. return len(G) == len(nodes) == sum(len(c) for c in communities)