标量乘法?

标量乘法?

问题描述:

我试图做一个scalar_multiplication lambda函数,但我只能让我的第一个断言工作。我认为我需要考虑多个抽象层次,但我被卡住了。以下是我迄今为止标量乘法?

scalar_mult = lambda c, M: [x * c for x in M] 

assert scalar_mult(1, [[1,2], [3,4]]) == [[1,2], [3,4]] 
assert scalar_mult(2, [[1,2], [3,4]]) == [[2,4], [6,8]] 

你的列表M有两级,因而需要迭代两次。根据您当前的代码

scalar_mult(2, [[1,2], [3,4]]) 

将导致

[[1,2,1,2], [3,4,3,4]] 

因为你是通过2复接第一列表中的每个元素,并在蟒蛇复接列表,一个整数简单地复制它。所以,你的代码做

[1, 2]*2 # which equals to [1,2,1,2] 

,并保存要作为新的列表的第一个元素,然后转到第二个和做类似的“错误”。

在另一方面

scalar_mult = lambda c, M: [[x * c for x in X] for X in M] 

应该正常工作。