Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and B.
Sample Input
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
Sample Output
6x^3 + 14x^2 + 2x + 6
Sample input
4
0 5
1 0
2 10
3 6
4
0 -5
1 0
2 -10
3 -6
Sample Output
Sample Input
5
0 2
1 0
2 1
4 7
3 6
5
2 4
3 3
4 5
0 1
1 0
Sample Output
12x^4 + 9x^3 + 5x^2 + 3
poly_dict = {}
print("Two polynomials summation")
for i in range(2):
poly_len = int(input("Enter polynomial length: "))
print("Enter orders and coefficients separated by space.")
for i in range(poly_len):
order_coefficient = input()
order, coefficient = map(int, order_coefficient.strip().split(" "))
if order in poly_dict.keys():
poly_dict[order] += coefficient
else:
poly_dict.update({order: coefficient})
i = 0
poly_list = []
while poly_dict != {}:
if i in poly_dict.keys():
poly_list.append(poly_dict[i])
del poly_dict[i]
else:
poly_list.append(0)
i += 1
answer = ""
for i in range(len(poly_list), 0, -1):
if i == 1:
x_power = ""
elif i == 2:
x_power = "x"
else:
x_power = 'x^' + str(i - 1)
if poly_list[i - 1] != 0:
if poly_list[i - 1] < 0:
answer = answer + str(poly_list[i - 1]) + x_power
elif i == len(poly_list):
answer = answer + str(poly_list[i - 1]) + x_power
else:
answer = answer + '+' + str(poly_list[i - 1]) + x_power
print("Answer is: ",answer)
Comments
Leave a comment