Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and B
For term Cix^Pi, if the coefficient of the term Ci is 1, simply print x^Pi instead of 1x^Pi.
If the degree of the polynomial is zero and the constant term is also zero, then just print 0 to represent the polynomial.
Sample Input
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
Sample Output
12x^4 + 9x^3 - 5x^2 - x - 1
M = int(input("M = "))
Mcp = []
for i in range(M):
Mcp.append([1, 1])
Mcp[i][0], Mcp[i][1] = map(int, input("Enter two integer (separated by a space): ").split())
N = int(input("N = "))
Ncp = []
for i in range(N):
Ncp.append([1, 1])
Ncp[i][0], Ncp[i][1] = map(int, input("Enter two integer (separated by a space): ").split())
A = []
for i in range(M):
if Mcp[i][0] == 0:
temp = str(Mcp[i][1])
elif Mcp[i][1] == 0:
continue
elif Mcp[i][0] == 1:
temp = str(Mcp[i][1]) + 'x'
elif Mcp[i][1] == 1:
temp = 'x^' + str(Mcp[i][0])
else:
temp = str(Mcp[i][1]) + 'x^' + str(Mcp[i][0])
A.append(temp)
print("A = ", end='')
for i in range(len(A)-1, -1, -1):
if i == 0:
print(str(A[i]))
else:
print(str(A[i]) + ' + ', end='')
B = []
for i in range(N):
if Ncp[i][0] == 0:
temp = str(Ncp[i][1])
elif Ncp[i][1] == 0:
continue
elif Ncp[i][0] == 1:
temp = str(Ncp[i][1]) + 'x'
elif Ncp[i][1] == 1:
temp = 'x^' + str(Ncp[i][0])
else:
temp = str(Ncp[i][1]) + 'x^' + str(Ncp[i][0])
B.append(temp)
print("B = ", end='')
for i in range(len(B)-1, -1, -1):
if i == 0:
print(str(B[i]))
else:
print(str(B[i]) + ' + ', end='')
A_and_B = []
key = 0
if M >= N:
for i in range(M):
A_and_B.append([1, 1])
for j in range(N):
if Mcp[i][0] == Ncp[j][0]:
A_and_B[i][1] = Mcp[i][1] + Ncp[j][1]
A_and_B[i][0] = Mcp[i][0]
key = 1
if key == 0:
A_and_B[i][1] = Mcp[i][1]
A_and_B[i][0] = Mcp[i][0]
key = 0
else:
for i in range(N):
A_and_B.append([1, 1])
for j in range(M):
if Ncp[i][0] == Mcp[j][0]:
A_and_B[i][1] = Ncp[i][1] + Mcp[j][1]
A_and_B[i][0] = Ncp[i][0]
key = 1
if key == 0:
A_and_B[i][1] = Ncp[i][1]
A_and_B[i][0] = Ncp[i][0]
key = 0
Result = []
for i in range(len(A_and_B)):
if A_and_B[i][0] == 0:
temp = str(A_and_B[i][1])
elif A_and_B[i][1] == 0:
continue
elif A_and_B[i][0] == 1:
temp = str(A_and_B[i][1]) + 'x'
elif A_and_B[i][1] == 1:
temp = 'x^' + str(A_and_B[i][0])
else:
temp = str(A_and_B[i][1]) + 'x^' + str(A_and_B[i][0])
Result.append(temp)
print("Result (A+B) = ", end='')
for i in range(len(Result)-1, -1, -1):
if i == 0:
print(str(Result[i]))
else:
print(str(Result[i]) + ' + ', end='')
Comments
Leave a comment