Answer to Question #206800 in Python for siva

Question #206800

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.

Sample Input:1 Sample Input2:

5 4

0 2 0 5

1 3 1 0

2 1 2 10

4 7 3 6

3 6

Output: Output: 6x^3 +10x^2+5

7x^4 + 6x^3 + x^2 + 3x + 2
1
Expert's answer
2021-06-14T03:01:04-0400
#Python 3.9.5


def tostring_polynom(p):
    res = ''
    first = True
    for Pi in sorted(p, reverse=True):
        Ci = p[Pi]
        if first:
            if Ci == 0 and Pi == 0:
                return '0'
            
            if Ci == 1 and Pi != 0:
                pass
            elif Ci == -1 and Pi != 0:
                res = '-'
            else:           
                res = f'{Ci}'
            first = False
            
        else:        
            if Ci > 0:
                res += ' + '
            elif Ci < 0:
                res += ' - '
            else:
                continue
            res += f'{abs(Ci)}'
        
        if Pi == 0:
            continue
        if Pi == 1:
            res += 'x'
        else:
            res += f'x^{Pi}'
    return res


def read_polynom():
    n = int(input())
    p = {}
    for i in range(n):
        L = input().split()
        Pi = int(L[0])
        Ci = int(L[1])
        p[Pi] = Ci
    return p


PiCi = read_polynom()
print(f'Result: {tostring_polynom(PiCi)}')

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

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS