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
答案 0 :(得分: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')