Answer to Question #167594 in Python for Sri

Question #167594

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.


Constraints


N <= 100

0 <= Pi < 1000

-1000 <= Ci <= 1000


Sample Input


5

0 2

1 3

2 1

4 7

3 6


Output:


7x^4 + 6x^3 + x^2 + 3x + 2
1
Expert's answer
2021-02-28T14:04:02-0500


#!/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()


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

Assignment Expert
05.04.21, 13:12

Dear Nikhil post a new question

Nikhil
04.04.21, 07:46

Input: 5 0 2 1 3 2 1 4 7 Expected Output: 7x^4 + 6x^3 + x^2 + 3x + 2 What I got with the above code is : 7x^4 + 6x^3 + 1x^2 + 3 + 2

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS