class - How can I multiply two polynomials in Python using a loop and by calling another function? -
i've been working @ problem couple hours now, don't know start or anything. understand math/logic behind it, don't know put code well.
this problem:
- write , test function multiply(self, other) returns product of 2 polynomials. use 1 loop(for or while); within call *multiply_by_one_term* previous question.
this have set in beginning, can't recall it's called:
class polynomial: def __init__(self, coeffs=[0]): self.coeffs = coeffs
this test have made:
def multiply(self, other): """ >>> p1 = polynomial([1, 2]) >>> p2 = polynomial([3, 4]) >>> p1.multiply(p2).coeffs [3, 10, 8] """
this function need call:
def multiply_by_one_term(self, a, exp): """ >>> p = polynomial([2, 1, 3]) >>> p.multiply_by_one_term(3, 2).coeffs [6, 3, 9, 0, 0] >>> p = polynomial([2, 1, 3]) >>> p.multiply_by_one_term(3, 0).coeffs [6, 3, 9] """ return polynomial([a*i in self.coeffs] + [0]*exp)
i appreciate if me this. i'm still noob when comes programming , don't know well.
mathematically, amount of coefficients we'll have in end (or power) should power of first polynomial plus power of second, generate list of many zeroes. iterate through coefficients of first polynomial. here i'm using enumerate keep track of index we're on. of course assuming power each number coefficient of same index. number in item 2 before x^2.
for each coefficient of polynomial one, loop through of coefficients of polynomial 2 (every coefficient of polynomial 2 needs multiplied every coefficient of polynomial one). resulting power addition of indices, taken care of final_coeffs[ind1 + ind2] += coef1 * coef2
. that's left return new polynomial object.
realize here p1 , p2 2 polynomial objects.
def multiply(p1, p2): final_coeffs = [0] * (len(p2.coeffs)+len(p1.coeffs)-1) ind1, coef1 in enumerate(p1.coeffs): ind2, coef2 in enumerate(p2.coeffs): final_coeffs[ind1 + ind2] += coef1 * coef2 return polynomial(final_coeffs)
Comments
Post a Comment