Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 383
Timothy Leung Avatar asked Jul 08 '13 07:07

Timothy Leung


People also ask

How do you add two lists in Python?

The sum() function is used to add two lists using the index number of the list elements grouped by the zip() function. A zip() function is used in the sum() function to group list elements using index-wise lists.


2 Answers

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)]
like image 119
John La Rooy Avatar answered Sep 30 '22 01:09

John La Rooy


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.

like image 41
JBernardo Avatar answered Sep 30 '22 02:09

JBernardo