我做了加法和减法,但我很难在python中乘以多项式.
例如,如果我有:
2X^2 + 5X + 1 [1,5,2]
Run Code Online (Sandbox Code Playgroud)
和...
3X^3 + 4X^2 + X + 6 [6,1,4,3]
Run Code Online (Sandbox Code Playgroud)
我们得到:
6X^5 + 23X^4 + 25X^3 + 21X^2 + 31X + 6 [6,31,21,25,23,6]
Run Code Online (Sandbox Code Playgroud)
我很绝望.我已经在这里工作了好几天.任何帮助,将不胜感激
我需要一些帮助,尤其是b).谢谢
为矩阵定义一个类,如下所示:(a)提供一个实现__init__,它将列表列表作为输入并返回一个matrix类型的新对象.
对于矩阵A =
1 2
3 4
Run Code Online (Sandbox Code Playgroud)
用户可以进入A = matrix( [[1,2],[3,4]]).
(b)提供一个实现__repr__,返回矩阵的字符串表示,在单独的行中打印每一行,例如将A打印为:
1, 2
3, 4
Run Code Online (Sandbox Code Playgroud) 我知道如何将两个矩阵相乘(在一个类下)。下面我展示我的代码。然而我似乎无法弄清楚如何在Python中将矩阵和整数相乘。
更新:矩阵示例。
L=[[1,2],[3,4],[5,6]]
3*L
# [[1,6],[9,12],[15,18]]
def __mul__(self,other):
'''this will multiply two predefined matrices where the number of
columns in the first is equal to the number of rows in the second.'''
L=self.L
L2=other.L
result=[]
if len(L[0])==len(L2):
for i in range(len(L)):
row=[]
for j in range(len(L2[0])):
var=0
for k in range(len(L2)):
var=var+L[i][k]*L2[k][j]
row=row+[var]
result = result+[row]
return matrix(result)
else:
raise ValueError('You may not only multiply m*n * n*q matrices.')
Run Code Online (Sandbox Code Playgroud) python ×3