Answer to Question #215872 in Python for aravind

Question #215872
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.
1
Expert's answer
2021-07-12T00:18:08-0400
n = int(input('N = '))
polinom = {}
k = 0
while k < n:
	ci, pi = input().split()
	ci, pi = int(ci), int(pi)
	if pi in polinom:
		polinom[pi] += ci
	else:
		polinom[pi] = ci
	k += 1
	s = ''
sorted_polinom = {}
for key in sorted(polinom, reverse=True):
	sorted_polinom[key] = polinom[key]


if len(polinom) == 0:
	pass
else:
	first = True
	for p in sorted_polinom:
		if sorted_polinom[p] == 0:
			continue
		if sorted_polinom[p] < 0:
			if first:
				s += '-'
			else:
				s += ' - '
		else:
			if not first:
				s += ' + '
		first = False
		if (abs(sorted_polinom[p]) == 1) and p == 0:
			s += '1'
			continue
		if abs(sorted_polinom[p]) != 1:
			s += str(abs(sorted_polinom[p]))
		if p < 0:
			s += 'x^({})'.format(p)
		elif p == 1:
			s += 'x'
		elif p > 0:
			s += 'x^{}'.format(p)
if len(s) == 0:
	print('0')
else:
	print(s)

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