Reputation: 69
I'm trying to write a function, polyprod(a,b), in Python that takes the input of two lists and then outputs a list.
The list is a polynomial, with the entry in a list corresponding to the coefficient of the power of x associated to that position. So for example, these lists will represent polynomials as follows:
[1,1,1] = 1 + x + x2, [0,2,6] = 2x + 6x2.
I want my function to take any two such lists, and output a list representing the product, so for our example we would get:
polyprod([1,1,1], [0,2,6]) = [0,2,8,8,6], since (1+x+x2)(2x+6x2) = 2x + 8x2 + 8x3 + 6x4.
I'm aware of the convolve function in Numpy, and I've tried to emulate what it does with the following code (without success). I'm quite new to Python and I'm aware that this could probably be quite wrong.
def polyprod(a,v):
prodav = [0]*(len(a)+len(v)-1)
if len(v) > len(a):
for n in range(len(a)):
for m in range(n+1):
prodav[n] += v[m]*a[n-m]
for n in range(len(v)):
for m in range(n+1):
prodav[n] += a[m]*v[n-m]
What is wrong in this code and how can I get the correct results using only standard libraries?
Upvotes: 1
Views: 796
Reputation: 350770
Looking at your code you can immediately see that the indexes at the right most side of the target list never get a value in these loops, as the index n only iterates up to the length of either input list.
The index to add a product to is determined by the sum of the indexes in the input lists:
def polyprod(a,v):
prodav = [0]*(len(a)+len(v)-1)
for n in range(len(a)):
for m in range(len(v)):
prodav[n+m] += v[m]*a[n]
return prodav
print(polyprod([1,1,1], [0,2,6])) # [0, 2, 8, 8, 6]
Upvotes: 1