Given two polynomials A and B, write a program that adds the given two polynomials A and B.
coef1 = []
coef2 = []
sum = []
print("Enter the degree of polynomial A: ", end='')
n1 = int(input())
for i in range(n1+1):
print(f"Enter the coefficient of x to the power {i}: ", end='')
coef1.append(int(input()))
print("\nEnter the degree of polynomial B: ", end='')
n2 = int(input())
for i in range(n2+1):
print(f"Enter the coefficient of x to the power {i}: ", end='')
coef2.append(int(input()))
print("\nPolynomial A:")
for i in range(n1+1):
if coef1[i] != 0:
if i == 0:
print(f"{coef1[i]} + ", end='')
elif i == 1:
print(f"{coef1[i]}x", end='')
elif i == (n1):
print(f" + {coef1[i]}x^{i}", end='')
else:
print(f" + {coef1[i]}x^{i}", end='')
print("\nPolynomial B:")
for i in range(n2+1):
if coef2[i] != 0:
if i == 0:
print(f"{coef2[i]} + ", end='')
elif i == 1:
print(f"{coef2[i]}x", end='')
elif i == (n2):
print(f" + {coef2[i]}x^{i}", end='')
else:
print(f" + {coef2[i]}x^{i}", end='')
if n1 < n2:
for i in range(n2+1):
sum.append(coef2[i])
for i in range(n1+1):
sum[i] += coef1[i]
else:
for i in range(n1+1):
sum.append(coef1[i])
for i in range(n2+1):
sum[i] += coef2[i]
print("\nSum Polynomials A an B:")
for i in range(len(sum)):
if sum[i] != 0:
if i == 0:
print(f"{sum[i]}", end='')
elif i == 1:
print(f" + {sum[i]}x", end='')
elif i == (len(sum)):
print(f" + {sum[i]}x^{i}", end='')
else:
print(f" + {sum[i]}x^{i}", end='')
Comments
Leave a comment