1
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

4

1 に答える 1

0

これは本当に munkres ライブラリのバグのようです。print_matrix は単なる「便利な」関数であり、バグ レポートを提出し、暫定的に次のようなものに置き換えることをお勧めします (これは、0 または負の数を対数)。やろうとしていたのは、各列が数値の最大幅になるように適切に配置することです。負の数を渡すと、問題が 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')
于 2015-06-07T16:57:05.827 に答える