Sharl
Sharl

Reputation: 175

Adding and scaling polynomials in python using class

I'm making a polynomial class but can't get the add and scale function to work properly.

The scale function should work by multiplying the coefficients of the polynomial by a given x. For example if y=2x^3+4x^2 and x=2, then y=4x^3+8x^2

The add function should just add like terms of two polynomials.

I've added comments to the code to hopefully explain how I was trying to get the functions to work

class Polynomial:

def __init__(self, coefficients):
    self.coeffs=coefficients

def scale(self, x):
    return Polynomial(self.coeffs*x)

def add(self, other):
    #getting the highest degree to add from
    self.degree=len(self.coeffs)-1
    other.degree=len(other.coeffs)-1

    maxcoeff=max(self.degree,other.degree)+1
    #adding 0's to the end of the shortest one to make adding easiers (pairwise)
    self_temp = self.coeffs + [0]*(maxcoeff-self.degree-1)
    other_temp = other.coeffs + [0]*(maxcoeff-other.degree-1)
    #adding elementwise
    coeffs = [self_temp[i] + other_temp[i] for i in range(len(other_temp))]
    return Polynomial(coeffs)

Upvotes: 0

Views: 947

Answers (1)

mementum
mementum

Reputation: 3203

This is not what you are looking for:

def scale(self, x):
    return Polynomial(self.coeffs*x)

With that multiplication you are growing/shrinking the list.

Because your coeffs is an iterable. This is what you want:

def scale(self, x):
    return Polynomial([c * x for c in self.coeffs])

And this:

self_temp = self.coeffs + [0]*(maxcoeff-self.degree-1)
other_temp = other.coeffs + [0]*(maxcoeff-other.degree-1)
coeffs = [self_temp[i] + other_temp[i] for i in range(len(other_temp))

Can possibly better be expressed as:

coeffs = [x + y for x, y in itertools.izip_longest(self.coeffs, other.coeffs, fillvalue=0)]

Upvotes: 3

Related Questions