Answer to Question #167110 in Python for Chandra sena reddy

Question #167110

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.


Output


Print the polynomial in the format Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0, where Pi's are powers in decreasing order, Ci is coefficient, and C0 is constant. There will be space before and after the plus or minus sign.

If the coefficient is zero, then don't print the term.

If the term with the highest degree is negative, the term should represent -Cix^Pi.

For the term where power is 1, represent it as C1x instead of C1x^1.

If the polynomial degree is zero and the constant term is also zero, then print 0 to represent the polynomial.

For term Cix^Pi, if the coefficient of the term Ci is 1, print x^Pi instead of 1x^Pi.


Explanation


If N = 4

For power 0, the coefficient is 5

For power 1, the coefficient is 0

For power 2, the coefficient is 10

For power 3, the coefficient is 6.

Then polynomial represents "6x^3 + 10x^2 + 5"


Constraints


N <= 100

0 <= Pi < 1000

-1000 <= Ci <= 1000



Sample Input

4

0 5

1 0

2 10

3 6


Sample Output

6x^3 + 10x^2 + 5

output 1 success, but

Sample input

5

0 2

1 3

2 1

4 7

3 6

expected:

7x^4 + 6x^3 + x^2 + 3x + 2

I got

6x^3 + 7x^4 + 1x^2 + 3x + 2
1
Expert's answer
2021-03-02T17:06:43-0500
#!/usr/bin/env python

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='')        

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

Vasu
15.05.22, 18:00

Thank you sir

Assignment Expert
03.03.21, 09:17

Dear chandrasena reddy, You're welcome. We are glad to be helpful. If you liked our service please press like-button beside answer field. Thank you!

chandrasena reddy
03.03.21, 07:26

Thankyou so much, for you help.

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS