Timothy Leung Timothy Leung - 1 year ago 106
Python Question

Add two lists of different lengths in python, start from the right

I want to add two list of different length start from the right
Here's an example

[3, 0, 2, 1]
[8, 7]


Expected result:

[3, 0, 10, 8]


These list represent coefficient of polynomials

Here is my implementation

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


This one work fine, just want to know anyway to do better, cleaner code?
As python always stressed at clean code, I want to know is there any way to write cleaner, pythonic code?

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

Obviously, if you choose a convention where the coefficients are ordered the opposite way, you can just use

P = [1, 2, 0, 3]
Q = [7, 8]
[x+y for x,y in izip_longest(P, Q, fillvalue=0)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download