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
Code:
#Get the number of N polynomial numbers
n = int(input())
#Get polynom A
polynomA=[0 for i in range(n)]
for i in range(0,n):
power,coefficient = input().split(' ')
polynomA[int(power)] = int(coefficient)
n = int(input())
#Get polynom B
polynomB=[0 for i in range(n)]
for i in range(0,n):
power,coefficient = input().split(' ')
polynomB[int(power)] = int(coefficient)
#Declare array polynomSum
polynomSum=[]
#if the length of array polynomA > polynomB
if(len(polynomA)>=len(polynomB)):
polynomSum=[0 for i in range(len(polynomA))]
for i in range(0,len(polynomA)):
#add zeros to the array polynomB
if(i>=len(polynomB)):
polynomB.append(0)
#calculate sum
polynomSum[i]=polynomA[i]+polynomB[i]
else:#if the length of array polynomA < polynomB
polynomSum=[0 for i in range(len(polynomB))]
for i in range(0,len(polynomB)):
#add zeros to the array polynomA
if(i>=len(polynomA)):
polynomA.append(0)
#calculate sum
polynomSum[i]=polynomA[i]+polynomB[i]
#Display result
if(sum(polynomSum)==0):
print("0")
else:
for power in range(len(polynomSum)-1,0,-1):
if polynomSum[power] != 0:
print(str(polynomSum[power]),'x^',str(power),' + ',end='')
print(polynomSum[0])
Examples:
0 2
1 0
2 1
4 7
3 6
5
2 4
3 3
4 5
0 1
1 0
12 x^ 4 + 9 x^ 3 + 5 x^ 2 + 3
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
6 x^ 3 + 14 x^ 2 + 2 x^ 1 + 6
3
0 1
1 2
2 4
4
0 5
1 0
2 10
3 6
6 x^ 3 + 14 x^ 2 + 2 x^ 1 + 6
Comments
Leave a comment