Reputation: 41
Can someone help me out with my code, the only answer I get is [0,0] for all inputs-:
def add_poly(a,b,n):
p=[]
for i in range((n*2)-2):
p.append(0)
for i in range(0,n-1):
for j in range(0,n-1):
p[i+j]=(a[i]*b[j])
return p
n=2
a=[1,3]
b=[0,2]
print(add_poly(a,b,n))
Upvotes: 1
Views: 79
Reputation: 114300
Your fundamental problem is that range
is exclusive on the high bound. To loop over n
elements, you do range(n)
, not range(n - 1)
. That will give you a loop over 0, 1, 2, ..., n-1
.
Another issue is that you're providing redundant information about the size of the polynomials. The degree is already encoded in their length. If you provide n
, that's redundant information, and may be wrong. E.g., what if you want to multiply a second order polynomial (n=3
) by a third order (n=4
)?
Finally, the operation you are attempting to implement seems like multiplication rather than addition.
So here is a sample of how to use len
to get the order of the polynomials, and enumerate
to place the elements. You can also preallocate the output list in one line:
def mult_poly(a, b):
p = [0] * (len(a) + len(b) - 1)
for i, x in enumerate(a):
for j, y in enumerate(b):
p[i + j] += x * y
return p
Upvotes: 2