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
发布于 2015-06-07 16:57:05
这看起来就像绿城库里的一个bug。print_matrix只是一个“方便”的函数,我建议您提交一个bug报告,并在此之前只使用以下内容替换它(这只是他们的代码,为了避免将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')https://stackoverflow.com/questions/30665430
复制相似问题