首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >库python的print_matrix对包含零的矩阵抛出一个异常。

库python的print_matrix对包含零的矩阵抛出一个异常。
EN

Stack Overflow用户
提问于 2015-06-05 11:30:46
回答 1查看 544关注 0票数 1
代码语言:javascript
复制
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中的代码片段:

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-07 16:57:05

这看起来就像绿城库里的一个bug。print_matrix只是一个“方便”的函数,我建议您提交一个bug报告,并在此之前只使用以下内容替换它(这只是他们的代码,为了避免将0或负数应用到对数中)。我们想要做的是将每一列的空间适当地设置为一个数字的最大宽度。请注意,如果您传递负数,这可能有一个1期,但另一方面,如果你有负成本,你可能有更大的问题。

代码语言:javascript
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30665430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档