Add two lists of different lengths in python, start from the right
Edit (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]
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 zip_longest(P, Q, fillvalue=0)]
I believe a simple for loop is far simpler than a comprehension with 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)
If you need to keep P
unchanged, copy it first. Also, if Q
is much smaller than P
, this will be more effective.