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