Answer to Question #203581 in Python for Sudheer

Question #203581

polinom = {}

for i in range(2):

n = int(input())

for item in range(n):

p, c = input().split(' ')

p, c = int(p), int(c)

if p in polinom:

polinom[p] += c

else:

polinom[p] = c

res = ''

if len(polinom) == 0:

pass

else:

flag = True

for p in polinom:

if polinom[p] == 0:

continue

if polinom[p] < 0:

if flag:

res += '-'

else:

res += ' - '

else:

if not flag:

res += ' + '

flag = False

if (abs(polinom[p]) == 1) and p == 0:

res += '1'

continue

if abs(polinom[p]) != 1:

res += str(abs(polinom[p]))

if p < 0:

res += 'x^({})'.format(p)

elif p == 1:

res += 'x'

elif p > 0:

res += 'x^{}'.format(p)

if len(res) == 0:

print('0')

else:

print(res)

Output:6 + 2x + 14x^2 + 6x^3
Expected output:6x^3 + 14x^2 + 2x + 6
1
Expert's answer
2021-06-05T23:52:19-0400
polinom = {}
for i in range(2):
    n = int(input('N: '))
    for item in range(n):
        p, c = [int(x) for x in input('P, C: ').split(' ')]
        if p in polinom:
            polinom[p] += c
        else:
            polinom[p] = c
res = ''
flag = True
for p in sorted(polinom, reverse=True):
    if polinom[p] == 0:
        continue
    elif polinom[p] < 0:
        if flag:
            res += '-'
            flag = False
        else:
            res += ' - '
    else:
        if flag:
            flag = False
        else:
            res += ' + '
    if (abs(polinom[p]) == 1) and p == 0:
        res += '1'
        continue
    if abs(polinom[p]) != 1:
        res += str(abs(polinom[p]))
    if p < 0:
        res += 'x^({})'.format(p)
    elif p == 1:
        res += 'x'
    elif p > 0:
        res += 'x^{}'.format(p)
if len(res) == 0:
    print('0')
else:
    print(res)

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

dnyanesh
11.09.21, 12:07

thanks a lot sirr!!!!!!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS