[英]matrix multiplication with scalar without numpy
I simply want to multiply a matrix with a scalar and have a correct output.我只是想将一个矩阵与一个标量相乘,并得到一个正确的 output。 My code works but it updates the old matrix with the new output.我的代码有效,但它使用新的 output 更新了旧矩阵。 I've used slices as copies but I can't seem to get it to work.我使用切片作为副本,但我似乎无法让它工作。 Numpy is not allowed for this. Numpy 不允许这样做。
I simply want to run this code multiple times on the same matrix and get the same output everytime.我只是想在同一个矩阵上多次运行这段代码,每次都得到相同的 output。
class Matrix:
def __init__(self, rows):
self.rows = rows[:]
self.copy = self.rows[:]
def scale(self, w):
copy = self.copy[:]
for i in range(len(copy)):
for j in range(len(copy)):
copy[i][j] = copy[i][j]*w
return copy
c = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
print(c.scale(10))
print(c.scale(10))
Output should be: Output 应该是:
[[10, 0, 0], [0, 10, 0], [0, 0, 10]] [[10, 0, 0], [0, 10, 0], [0, 0, 10]]
[[10, 0, 0], [0, 10, 0], [0, 0, 10]] [[10, 0, 0], [0, 10, 0], [0, 0, 10]]
Instead it's取而代之的是
[[10, 0, 0], [0, 10, 0], [0, 0, 10]] [[10, 0, 0], [0, 10, 0], [0, 0, 10]]
[[100, 0, 0], [0, 100, 0], [0, 0, 100]] [[100, 0, 0], [0, 100, 0], [0, 0, 100]]
Since the OP says that he is not allowed to use imports, the following alternative has its own implementation of deepcopy:由于 OP 说他不允许使用导入,因此以下替代方案有自己的 deepcopy 实现:
class Matrix:
def __init__(self, rows):
self.rows = rows[:]
def deepcopy(self):
rows = [[elem for elem in row]
for row in self.rows
]
return Matrix(rows)
def scale(self, w):
copy = self.deepcopy()
copyr = copy.rows
for i in range(len(copyr)):
for j in range(len(copyr)):
copyr[i][j] = copyr[i][j] * w
return copyr
c = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
print(c.scale(10))
print(c.scale(10))
This is one of those subtleties of Python.这是 Python 的微妙之处之一。 Your code only creates one object containing the data.您的代码仅创建一个包含数据的 object。 When you assign self.copy = self.rows[:]
, you don't get a new copy of the data, you only create a new reference to the same object.当您分配self.copy = self.rows[:]
时,您不会获得数据的新副本,您只会创建对相同 object 的新引用。 Python has a built-in facility for making a deep copy. Python 具有用于制作深拷贝的内置工具。
from copy import deepcopy
class Matrix:
def __init__(self, rows):
self.rows = rows[:]
def scale(self, w):
copy = deepcopy(self.rows)
for i in range(len(copy)):
for j in range(len(copy)):
copy[i][j] = copy[i][j] * w
return copy
c = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
print(c.scale(10))
print(c.scale(10))
Output: Output:
[[10, 0, 0], [0, 10, 0], [0, 0, 10]]
[[10, 0, 0], [0, 10, 0], [0, 0, 10]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.