Skip to content

Bug: ZeroDivisionError when graph has zero-weight edges #106

@aryantusharr

Description

@aryantusharr

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:

  1. Be skipped/ignored during the algorithm execution, OR
  2. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions