Add two polynomials
write a program that adds the given two polynomials A and B.
Input
The first line contains a single integer M.
Next M lines contain two integers Pi, Ci of poly A
After that next line contains a single integer N.
Next N lines contain two integers Pj, Cj of poly B
Output
Print the addition of poly's A and B.
The format for printing polynomials is: Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0, where Pi's are powers in decreasing order, Ci is co-efficient and C0 is constant, there will be space before and after the plus or minus sign.
If co-eff is zero then don't print the term.
If the term with highest degree is negative, the term should be represented as -Cix^Pi.
For the term where power is 1 represent it as C1x instead of C1x^1.
If the degree of poly is zero and the constant term is also zero, then just print 0 to represent the poly.
For term Cix^Pi, if the coefficient of the term Ci is 1, simply print x^Pi instead of 1x^Pi.
Sample input
4
0 5
1 0
2 10
3 6
4
0 -5
1 0
2 -10
3 -6
Expected output
m = int(input("Enter M: "))
dic1 = {}
for i in range(0, m):
temp = [int(i) for i in input().split()]
dic1[temp[0]] = dic1.get(temp[0], 0) + temp[1]
n = int(input("Enter N: "))
dic2 = {}
for i in range(0, n):
temp = [int(i) for i in input().split()]
dic2[temp[0]] = dic2.get(temp[0], 0) + temp[1]
# dic1 + dic2 by keys and sort
for i in dic2.keys():
dic1[i] = dic1.get(i,0) + dic2[i]
tmp = sorted(dic1, reverse=True)
result = ''
for b in tmp:
if dic1[b]!=0:
result+= str(dic1[b]) + ' '
if result!='':
print(result)
else: print(0)
Comments
Leave a comment