我想从右边开始添加两个不同长度的列表这是一个例子
[3, 0, 2, 1]
[8, 7]
预期结果:
[3, 0, 10, 8]
这些列表代表多项式的系数
这是我的实现
class Polynomial:
def __init__(self, coefficients):
self.coeffs = coefficients
def coeff(self, i):
return self.coeffs[-(i+1)]
def add(self, other):
p1 = len(self.coeffs)
p2 = len(other.coeffs)
diff = abs(p1 - p2)
if p1 > p2:
newV = [sum(i) for i in zip(self.coeffs, [0]*diff+other.coeffs)]
else:
newV = [sum(i) for i in zip([0]*diff+self.coeffs, other.coeffs)]
return Polynomial(newV)
def __add__(self, other):
return self.add(other).coeffs
这个工作正常,只是想知道无论如何要做得更好,更清洁的代码?由于python总是强调干净的代码,我想知道有没有办法编写更干净的pythonic代码?