Answer to Question #212698 in Python for loop

Question #212698
 code in  Question #175894  gives result:12x^4 + 9x^3 + -5x^2 - 1x - 1 but 12x^4 + 9x^3 - 5x^2 - x - 1 is desired output.
how to get desired result .
input = 
5
0 -2
3 6
4 7
1 -3
2 -1
5
0 1
1 2
2 -4
3 3
4 5


 Question #175894 




1
Expert's answer
2021-07-02T04:11:15-0400
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

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS