Answer to Question #207275 in Python for Siva

Question #207275

Given polynomial, write a program that prints polynomial in Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0 format.

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.

For term Cix^Pi, if the coefficient of the term Ci is 1, print x^Pi instead of 1x^Pi.

Explanation

If N = 4 If N = 5


If N=4
polynomial represents "6x^3+10x^2+5"   
If N=5
polynomial represents "7x^4+6x^3+x^2+3x+2"
1
Expert's answer
2021-06-15T07:08:51-0400
N = int(input('N = '))
polinom = {}
for i in range(N):
	power_i, coef_i = input(f'pow{i} coef{i} ').split()
	power_i, coef_i = int(power_i), int(coef_i)
	if power_i not in polinom:
		polinom[power_i] = coef_i
	else:
		polinom[power_i] += coef_i


if len(polinom) == 0:
	print('0')
else:
	str_polinom = ''
	for power_i in sorted(polinom, reverse=True):
		if polinom[power_i] == 0:
			continue
		elif polinom[power_i] < 0:
			if len(str_polinom) == 0:
				str_polinom += '-'
			else:
				str_polinom += ' - '
		else:
			if len(str_polinom) > 0:
				str_polinom += ' + '
		if (abs(polinom[power_i]) == 1) and power_i == 0:
			str_polinom += '1'
			continue
		elif abs(polinom[power_i]) != 1:
			str_polinom += str(abs(polinom[power_i]))
		if power_i < 0:
			str_polinom += f'x^({power_i})'
		elif power_i == 1:
			str_polinom += 'x'
		elif power_i > 0:
			str_polinom += f'x^{power_i}'
	if len(str_polinom) == 0:
		print('0')
	else:
		print(str_polinom)

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