munkres 库 python 的 print_matrix 在包含零的矩阵上抛出异常

print_matrix of munkres library python throws an exception on matrix containing zeroes

Lowest cost through this matrix:
Traceback (most recent call last):
    File "muncre.py", line 8, in <module>
        print_matrix(matrix, msg='Lowest cost through this matrix:')
    File "/usr/lib/python2.7/dist-packages/munkres.py", line 730, in    print_matrix
        width = max(width, int(math.log10(val)) + 1)
ValueError: math domain error

当矩阵的任何行中包含零时,将抛出上述错误。我该如何解决?

这是python中的一段代码:

from munkres import Munkres, print_matrix
matrix = [[6, 9, 1],
          [10, 9, 2],
          [0,8,7]]
m = Munkres()
indexes = m.compute(matrix)
print_matrix(matrix, msg='Lowest cost through this matrix:')
total = 0
for row, column in indexes:
    value = matrix[row][column]
    total += value
    print '(%d, %d) -> %d' % (row, column, value)
print 'total cost: %d' % total

我在 Ubuntu 中使用以下命令安装了库 munkres:

sudo apt-get install python-munkres

这看起来确实像是 munkres 库的错误。 print_matrix 只是一个 "convenience" 函数,我建议提交错误报告,并在此期间将其替换为类似以下内容(这只是他们的代码,带有修复程序以避免尝试应用0 或负数的对数)。那里试图做的是正确地 space 每列成为数字的最大宽度。请注意,如果您传入负数,这可能会导致 off by 1 问题,但另一方面,如果您的成本为负数,则可能会出现更大的问题。

def print_matrix(matrix, msg=None):
    """
    Convenience function: Displays the contents of a matrix of integers.
    :Parameters:
        matrix : list of lists
            Matrix to print
        msg : str
            Optional message to print before displaying the matrix
    """
    import math

    if msg is not None:
        print(msg)

    # Calculate the appropriate format width.
    width = 1
    for row in matrix:
        for val in row:
            if abs(val) > 1:
               width = max(width, int(math.log10(abs(val))) + 1)

    # Make the format string
    format = '%%%dd' % width

    # Print the matrix
    for row in matrix:
        sep = '['
        for val in row:
            sys.stdout.write(sep + format % val)
            sep = ', '
        sys.stdout.write(']\n')