Answer to Question #206630 in Python for siva

Question #206630

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

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-06-13T18:18:13-0400
while True:
	try:
		N = int(input('N '))
		break
	except ValueError:
		print('N must be integer')
		continue
pol = []
k = 0
while k < N:
	try:
		pi, ci = input('pi ci ').split()
		pi, ci = int(pi), int(ci)
	except ValueError:
		continue
	flag = True
	for i in range(len(pol)):
		if pol[i][0] == pi:
			pol[i][1] += ci
			flag = False
			break
	if flag:
		pol.append([pi, ci])
	k += 1
pol = sorted(pol, reverse=True, key=lambda k : k[0])


s = ''
if len(pol) == 0:
	print(0)
else:
	f = True
	for el in pol:
		if el[1] == 0:
			continue
		if el[1] < 0:
			if f:
				s += '-'
			else:
				s += ' - '
		else:
			if not f:
				s += ' + '
		f = False
		if (abs(el[1]) == 1) and el[0] == 0:
			s += '1'
			continue
		if abs(el[1]) != 1:
			s += str(abs(el[1]))
		if el[0] < 0:
			s += 'x^({})'.format(el[0])
		elif el[0] == 1:
			s += 'x'
		elif el[0] > 0:
			s += 'x^{}'.format(el[0])
	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