Install & Compatibility
Where this runs
tested against v1.1.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.012s · 17.8MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 1.5s · import 0.013s · 18MB
16MB installed
● package 16MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Munkres
✓ from munkres import Munkres
The primary class for running the algorithm.
DISALLOWED
✓ from munkres import Munkres, DISALLOWED
Constant to mark impossible assignments in the cost matrix.
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}')
Debug
Known issues
breakingAs of version 1.1.0, the `munkres` library dropped support for Python 2. Users on Python 2 must use an older version (pre-1.1.0).fixUpgrade to Python 3 or use `munkres` version < 1.1.0 if Python 2 is strictly required.
affects: >=1.1.0
gotchaThe Munkres algorithm natively solves minimization problems. To solve maximization problems (e.g., maximizing profit), the cost matrix must be transformed. A common approach is to subtract all matrix elements from a sufficiently large constant (e.g., the maximum value in the matrix).fixTransform your profit matrix `P` into a cost matrix `C` by `C[i][j] = MAX_PROFIT - P[i][j]`, where `MAX_PROFIT` is greater than or equal to any profit in the matrix.
affects: All
gotchaThe `munkres` module automatically pads rectangular cost matrices with zeros to make them square, as the algorithm requires a square matrix. However, this operation works on a *copy* of the input matrix, so the caller's original matrix is not modified.fixBe aware that the input matrix is copied and potentially padded. If you need to observe the padded matrix for debugging or further processing, manually pad it before passing it to `Munkres.compute()`.
affects: All
gotchaUsing the `DISALLOWED` constant correctly marks an assignment as impossible. However, if using `DISALLOWED` results in a scenario where a row or column has no possible valid assignments, the `compute` method will raise an `UnsolvableMatrix` exception, indicating that no complete assignment can be found under the given constraints.fixEnsure that your `DISALLOWED` constraints still allow for at least one valid assignment path for every row and column. If intentional non-assignments are needed, `munkres` does not directly support 'no match' if it leads to an unsolvable matrix. Consider augmenting your matrix with dummy rows/columns with zero costs to represent unassigned items if that aligns with your problem.
affects: All
gotchaThe utility function `munkres.print_matrix()` might raise a `ValueError` (e.g., `math.log10(0)`) if the matrix contains zero values, especially in older versions or specific Python environments. This function is for display and does not affect the core algorithm.fixIf encountering issues, avoid `print_matrix()` and implement a custom matrix printing function, or ensure only positive values are passed to it.
affects: <=1.1.4 (potentially fixed in future, but reported in past)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'munkres'
The `munkres` library has not been installed in your Python environment or the environment where you are running your script.
fixInstall the library using pip: `pip install munkres`
ValueError: math domain error (from print_matrix function when matrix contains zeros)
The `print_matrix` utility function in the `munkres` library attempts to use `math.log10` to format column widths, which raises a `ValueError` if any matrix element is zero because `log10(0)` is undefined.
fixAvoid using `munkres.print_matrix` with matrices containing zero values. Instead, iterate through the matrix and print it manually, or implement a custom printing function that handles zeros appropriately:
```python
def custom_print_matrix(matrix):
for row in matrix:
print(' '.join([str(x) for x in row]))
# Example usage:
# from munkres import Munkres
# m = Munkres()
# matrix = [,,]
# indexes = m.compute(matrix)
# custom_print_matrix(matrix)
``` Incorrect assignment results or non-optimal solutions (conceptual error)
The Munkres (Hungarian) algorithm solves the *assignment problem* on *bipartite graphs* (e.g., matching workers to jobs with minimum cost). If you are trying to solve a more general matching problem (e.g., matching users to other users within a single set), the `munkres` library will not provide the correct or optimal solution because it's designed for a specific type of problem.
fixEnsure your problem fits the definition of a bipartite matching problem. If you need to solve a general matching problem (non-bipartite), consider using an algorithm like the Blossom algorithm, which is implemented in libraries such as SciPy's `scipy.optimize.linear_sum_assignment` for linear sum assignment (which `munkres` also does) or dedicated graph libraries for general matching.
Upgrade
Version history
1.1.4latest on PyPI · released Sep 15, 2020
Audit
Dependencies
No dependency data recorded yet.