Add two Polynomials
Given two Polynomials A and B,write a program that adds the given two Polynomials A and B.
Sample input 1
4
0 5
1 0
2 10
3 6
Sample Output 1
Sample Input 2
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
Sample output 2
6x^3 + 14x^2 + 2x + 6
#!/usr/bin/env python
n = int(input())
# input tuples of Pi and Ci
PiCi = []
for i in range(n):
l = input().split()
Pi = int(l[0])
Ci = int(l[1])
PiCi.append((Pi, Ci))
PiCi.sort(reverse = True)
first = True
for Pi, Ci in PiCi:
# print Coefficent
if Ci == 0:
continue
if Ci < 0.0:
if first:
print(Ci, end = '')
else :
print(' -', abs(Ci), end = '')
else :
if first:
print(Ci, end = '')
else :
print(' +', abs(Ci), end = '')
first = False
# print x ^ Pi
if Pi == 0:
continue
if Pi == 1:
continue
if Pi < 0:
print(f 'x^({Pi})', end = '')
else :
print(f 'x^{Pi}', end = '')
print()
Comments
Leave a comment