Answer to Question #205577 in Python for Ayushi

Question #205577

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


input : 5

0 2

1 3

2 1

4 7


expected output : 7x^4 + 6x^3 - x^2 - 3x - 2
    your output:  7x^4 + 6x^3 - 1x^2 - 3x - 2


please explain this why this is again show error

i am using python 3.9 version




1
Expert's answer
2021-06-13T00:04:43-0400
def input_polinom():
	n = int(input())
	polinom = {}
	k = 0
	while k < n:
		try:
			pi, ci = input().split()
			pi, ci = int(pi), int(ci)
		except ValueError:
			continue
		if pi in polinom:
			polinom[pi] += ci
		else:
			polinom[pi] = ci
		k += 1
	res = {}
	for key in sorted(polinom.keys(), reverse=True):
		res[key] = polinom[key] 
	return res




def print_polinom(polinom:dict):


	s = ''
	if len(polinom) == 0:
		pass
	else:
		first = True
		for p in polinom:
			if polinom[p] == 0:
				continue
			if polinom[p] < 0:
				if first:
					s += '-'
				else:
					s += ' - '
			else:
				if not first:
					s += ' + '
			first = False
			if (abs(polinom[p]) == 1) and p == 0:
				s += '1'
				continue
			if abs(polinom[p]) != 1:
				s += str(abs(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)


polinom = input_polinom()
print_polinom(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
APPROVED BY CLIENTS