Thursday, July 22, 2010

Adding Polynomials

Imagine a polynomial like 2x3 - 3x2 + 5 was represented as a list of coefficients in a list like [1, -3, 0, 5]

My goal is to write a function that takes two lists and does polynomial addition on them. Ex: poly_add( [1, -2, 0, 3, 5] , [3, -1, 2] ) should return [1, -2, 3, 2, 7]

After a little brainstorming, I got this cute idea, which I felt was so cute that I should blog about it. Moreover it has been a while since I have written something.

Here is the function

def poly_add( x, y):
min_len = min( len(x), len(y))
return x[: -min_len] + y[: -min_len] + [ x[i] + y[i] for i in range(-min_len,0) ]

If this is trivial then great. If it is not so trivial, you will love the beauty behind this function and hence python itself.

I use Python and I am loving it :) :) :)

2 comments: