Description
The best_partition() and modularity() functions crash with ZeroDivisionError when the graph contains edges with zero weight. This is an edge case that should be handled gracefully.
Steps to reproduce
import networkx as nx
from community import best_partition, modularity
# Create a graph with zero-weight edges
G = nx.Graph()
G.add_weighted_edges_from([(0, 1, 0.0), (1, 2, 0.0)])
# This crashes with ZeroDivisionError:
partition = best_partition(G)
q = modularity(partition, G, weight='weight')
Expected behavior
Zero-weight edges represent "no connection" and should either:
- Be skipped/ignored during the algorithm execution, OR
- Return a meaningful error message instead of crashing
The function should not raise an unhandled ZeroDivisionError.
Root cause
The modularity calculation in the algorithm divides by the edge weight without first checking whether the weight is zero.
Environment
- python-louvain: 0.16
- networkx: 3.6.1
- Python: 3.14.5
Description
The
best_partition()andmodularity()functions crash withZeroDivisionErrorwhen the graph contains edges with zero weight. This is an edge case that should be handled gracefully.Steps to reproduce
Expected behavior
Zero-weight edges represent "no connection" and should either:
The function should not raise an unhandled
ZeroDivisionError.Root cause
The modularity calculation in the algorithm divides by the edge weight without first checking whether the weight is zero.
Environment