Polynomial
Given polynomial,write a program that prints polynomial in Cix^Pi + Ci-1x^Pi-1+....+C1x+C0 format.
Input
The first line contains a single Integer N.
Next N lines contain two integers Pi,Ci separated with space, where Pi denotes power and Ci denotes coefficient of Pi.
Sample Input 1
5
0 2
1 3
2 1
4 7
Sample output 1
7x^4 + 6x^3 + x^2 + 3x + 2
Sample input 2
4
0 5
1 0
2 10
3 6
Sample output 2
6x^3 + 10x^2 + 5
N = int(input())
C = [] # coefficients
P = [] # powers
for _ in range(N):
s = input()
s = s.split()
P.append(int(s[0]))
C.append(int(s[1]))
indx = sorted(range(len(P)), key= P.__getitem__, reverse=True)
if P[0] == 0 and C[0] == 0:
print(0)
exit()
for i in indx:
if C[i] > 0:
if i != indx[0]:
print(' + ', end='')
elif C[i] < 0:
if i != indx[0]:
print(' - ', end='')
else:
print('-', end='')
else: # Ci == 0
continue
if abs(C[i]) != 1:
print(abs(C[i]), end='')
if P[i] == 0:
print()
exit()
if P[i] == 1:
print('x', end='')
else:
print(f'x^{P[i]}', end='')
Comments
Leave a comment