Answer to Question #235296 in Python for rasi

Question #235296

Add two polynomials: Given two polynomials A and B, write a program that adds the given two polynomials A and B.


input:

4

0 5

1 0

2 10

3 6

4

0 -5

1 0

2 -10

3 -6


output:0



1
Expert's answer
2021-09-09T11:02:54-0400
def add_polinom(p):


	n = int(input())
	for i in range(n):
		pi, ci = input().split()
		pi, ci = int(pi), int(ci)
		if pi in p:
			p[pi] += ci
		else:
			p[pi] = ci
	return p


def polinom_to_string(p):


	s = ''
	flag = True
	for key in p:
		if p[key] == 0:
			continue
		if flag:
			if p[key] < 0:
				s += '-'
				p[key] *= -1
			flag = False
		else:
			if p[key] < 0:
				s += ' - '
				p[key] *= -1
			elif p[key] > 0:
				s += ' + '
		if p[key] != 1:
			s += f'{p[key]}'
			if key == 0:
				continue
			elif key == 1:
				s += 'x'
			else:
				s += f'x^{key}'
		else:
			if key == 0:
				s += '1'
			elif key == 1:
				s += 'x'
			else:
				s += f'x^{key}'
	if len(s) == 0:
		s = '0'
	return s


def sort_polinom(p):
	keys = list(p.keys())
	keys.sort(reverse=True)
	res = {}
	for el in keys:
		res[el] = p[el]
	return res




polinom = {}


for i in range(2):
	polinom = add_polinom(polinom)


polinom = sort_polinom(polinom)
print(polinom_to_string(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