So my teacher wants us to design a short program to add 2 polynomials, asking the user for the degree and coefficients, and print out the new coefficients.
ie:
poly1 deg=2 coeff= 3 4 5
poly2 deg=2 coeff= 2 5 6
output would be: 5 9 11

however, sometimes one would have a higher degree.

I have written:

Poly1=[]
deg=eval(input("enter degree"))
count=1
while count<=deg+1:
coeff=eval(input("enter coefficient"))
Poly1.append(coeff)
count+=1
Poly2=[]
deg2=eval(input("enter 2nd degree"))
count=1
while count<= deg2+1:
coeff=eval(input("enter 2nd coefficient"))
Poly2.append(coeff)
count+=1
max=0
if len(Poly1)>len(Poly2):
max=Poly1
else:
max=Poly2
index=-1
sum=[]
while index<=len(max):
sum=Poly1[index]+ Poly2[index]
index-=1
print(sum)

all of it is ok until i come to establishing a max and adding them. i am a new programmer so i know my syntax is very bad. i am trying to determine the max and then use the last elements of each and add them, and then move the index of the list over to the left to add right to left.
any ideas? thanks

Collapse Post « So my teacher wants us to design a short program to add 2 polynomials, asking the user for the degree and coefficients, and print out the new coefficients.
ie:
poly1 deg=2 coeff= 3 4 5
poly2 deg=2 coeff= 2 5 6
output would be: 5 9 11

however, sometimes one would have a higher degree.

I have written:

Poly1=[]
deg=eval(input("enter degree"))
count=1
while count<=deg+1:
coeff=eval(input("enter coefficient"))
Poly1.append(coeff)
count+=1
Poly2=[]
deg2=eval(input("enter 2nd degree"))
count=1
while count<= deg2+1:
coeff=eval(input("enter 2nd coefficient"))
Poly2.append(coeff)
count+=1
max=0
if len(Poly1)>len(Poly2):
max=Poly1
else:
max=Poly2
index=-1
sum=[]
while index<=len(max):
sum=Poly1[index]+ Poly2[index]
sum.append(sum)
index-=1
print(sum)

all of it is ok until i come to establishing a max and adding them. i am a new programmer so i know my syntax is very bad. i am trying to determine the max and then use the last elements of each and add them, and then move the index of the list over to the left to add right to left.
any ideas? thanks

Use the CODE button, then paste correctly indented code.

``````Poly1=[]
deg=eval(input("enter degree"))
count=1
while count<=deg+1:
coeff=eval(input("enter coefficient"))
Poly1.append(coeff)
count+=1
Poly2=[]
deg2=eval(input("enter 2nd degree"))
count=1
while count<= deg2+1:
coeff=eval(input("enter 2nd coefficient"))
Poly2.append(coeff)
count+=1
if len(Poly1)>len(Poly2):
len_poly_sum = len(Poly1)
else:
len_poly_sum = len(Poly2)
sum=[]
index=0
while index < len_poly_sum:
sum2=Poly1[index]+ Poly2[index]
index+=1
sum.append(sum2)
print(sum)``````

Don't repeat code, write function. Maybe better to use for with enumerate and zip functions instead of whil loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.