Skip to main content
 首页 » 编程设计

python之如何像计算机科学家一样思考(第 9 章): I don't understand the following

2025年05月04日13kuangbin

我发现很难理解以下代码中的 doctest 在函数中寻找的内容。

有人能帮我说清楚吗?

Question 14 :

  1. Write functions row_times_column and matrix_mult:
def row_times_column(m1, row, m2, column): 
    """ 
      >>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 0) 
      19 
      >>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 1) 
      22 
      >>> row_times_column([[1, 2], [3, 4]], 1, [[5, 6], [7, 8]], 0) 
      43 
      >>> row_times_column([[1, 2], [3, 4]], 1, [[5, 6], [7, 8]], 1) 
      50 
    """ 
def matrix_mult(m1, m2): 
   """ 
      >>> matrix_mult([[1, 2], [3,  4]], [[5, 6], [7, 8]]) 
      [[19, 22], [43, 50]] 
      >>> matrix_mult([[1, 2, 3], [4,  5, 6]], [[7, 8], [9, 1], [2, 3]]) 
      [[31, 19], [85, 55]] 
      >>> matrix_mult([[7, 8], [9, 1], [2, 3]], [[1, 2, 3], [4, 5, 6]]) 
      [[39, 54, 69], [13, 23, 33], [14, 19, 24]] 
    """ 

Add your new functions to matrices.py and be sure it passes the doctests above.

请您参考如下方法:

它要求您实现一些矩阵乘法方法。

在第一个中,给定一个矩阵,将 m1 的行乘以 m2 的列。第一个给出的是:

1 2   times   5 6 
3 4           7 8 

但我们只想要第 0 行乘以第 0 列,所以它会是

[1 2] x 5  
        7 

= 5+14 = 19。其他的依此类推...

第二个函数需要全矩阵乘法。参见 http://en.wikipedia.org/wiki/Matrix_multiplication