8

我想从右边开始添加两个不同长度的列表这是一个例子

[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代码?

4

5 回答 5

19

编辑(2020-18-03):

>>> P = [3, 0, 2, 1]
>>> Q = [8, 7]
>>> from itertools import zip_longest
>>> [x+y for x,y in zip_longest(reversed(P), reversed(Q), fillvalue=0)][::-1]
[3, 0, 10, 8]

显然,如果您选择系数以相反方式排序的约定,则可以使用

P = [1, 2, 0, 3]
Q = [7, 8]
[x+y for x,y in zip_longest(P, Q, fillvalue=0)]
于 2013-07-08T07:37:25.547 回答
2

我相信一个简单的 for 循环比使用 zip_longest 的理解要简单得多......

P = [3, 0, 2, 1]
Q = [8, 7]

A, B = sorted([P, Q], key=len)

for i, x in enumerate(reversed(A), 1):
   B[-i] += x

#print(B)

如果需要保持P不变,请先复制。此外,如果Q远小于P,这将更有效。

于 2013-07-08T07:41:42.217 回答
0

您可以使用numpy

>>> import numpy as np
>>> L1 = [3, 0, 2, 1]
>>> L2 = [8, 7]
>>> L2 = [0 for i in range(len(L1)-len(L2))] + L2
>>> A1 = np.array(L1)
>>> A2 = np.array(L2)
>>> A1+A2
array([ 3,  0, 10,  8])
于 2013-07-08T07:41:53.047 回答
0
a = [0, 1, 3, 4]

b = [5, 6]

iter_len = len(a)-(len(b) - 1)

for j in range(len(a), 0, -1):

        if j-iter_len < 0:
            break
        else:
            a[j-1] = a[j-1] + b[j-iter_len]
print a
于 2017-05-23T09:27:10.960 回答
0
a = [1,2,3,4,5,6,7,8,9,10,5,7,9]

b = [1,2,5]

n = a

addStart = len(a) - len(b)

count = 0

for i in b :

    n[addStart+count] = i + a[addStart+count]
    count+=1
print n
于 2017-05-23T09:37:10.297 回答