Answer to Question #202698 in Python for sudheer

Question #202698

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




If the add polynomials is euqal to zero it should print output:"0"


1
Expert's answer
2021-06-03T13:42:17-0400
def input_polinom():
	n = int(input('N = '))
	polinom = {}
	k = 0
	while k < n:
		try:
			ci, pi = input('c{} p{}: '.format(k+1, k+1)).split()
			ci, pi = int(ci), int(pi)
		except ValueError:
			continue
		if pi in polinom:
			polinom[pi] += ci
		else:
			polinom[pi] = ci
		k += 1
	return polinom


def summ_polinoms(A:dict, B:dict):


	for key in B:
		if key in A:
			A[key] += B[key]
		else:
			A[key] = B[key]
	C = {}
	for k in sorted(A.keys(), reverse=True):
		C[k] = A[k]
	return C


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)


a = input_polinom()
b = input_polinom()
c = summ_polinoms(a, b)
print_polinom(c)

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