Munkres (Hungarian) Algorithm

1.1.4 · maintenance · verified Wed Apr 15

The `munkres` library (version 1.1.4) provides a Python implementation of the Munkres (also known as the Hungarian) algorithm for solving the assignment problem, which aims to find a minimum-cost bipartite matching. It typically runs in O(n^3) time. While its original GitHub repository (linked on PyPI) is marked as unmaintained, the PyPI package remains available and provides a robust solution for assignment problems.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a cost matrix, initialize the Munkres solver, and compute the optimal (minimum cost) assignments. It also shows how to use the `DISALLOWED` constant for impossible assignments. The `compute` method returns a list of (row, column) tuples representing the optimal assignments.

from munkres import Munkres, DISALLOWED

def create_cost_matrix():
    # Example cost matrix: 3 workers, 3 tasks
    # cost[i][j] is cost of worker i doing task j
    return [
        [5, 9, 1],
        [10, 3, DISALLOWED],
        [8, 7, 4]
    ]

m = Munkres()
matrix = create_cost_matrix()

# The algorithm operates on a copy of the matrix,
# so the original 'matrix' is not modified.
indexes = m.compute(matrix)

total_cost = 0
print('Assignments:')
for row, column in indexes:
    value = matrix[row][column]
    total_cost += value
    print(f'  Worker {row} assigned to task {column} with cost {value}')

print(f'Total cost: {total_cost}')

view raw JSON →