Answer to Question #205581 in Python for Ayushi

Question #205581

input:

5

0 -2

3 6

4 7

1 -3


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

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


for this code this is the error

and i am using python 3.9



1
Expert's answer
2021-06-13T07:05:55-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
		not_in = True
		for i in range(len(polinom)):
			if polinom[i][0] == pi:
				polinom[i][1] += ci
				not_in = False
				break
		if not_in:
			polinom.append([pi, ci])
		k += 1
	return sorted(polinom, reverse=True, key=lambda k : k[0])


def print_polinom(polinom:list):
	s = ''
	if len(polinom) == 0:
		pass
	else:
		first = True
		for el in polinom:
			if el[1] == 0:
				continue
			if el[1] < 0:
				if first:
					s += '-'
				else:
					s += ' - '
			else:
				if not first:
					s += ' + '
			first = 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)


	print_polinom(input_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