0% found this document useful (0 votes)
12 views

4

Uploaded by

jondhaleom7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

4

Uploaded by

jondhaleom7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

//Group B -2nd CLL

//code :

class Node:
def __init__(self, coefficient, exponent):
self.coefficient = coefficient
self.exponent = exponent
self.next = None

def create_polynomial(terms):
polynomial = None
for i in range(terms):
coefficient, exponent = map(int, input(f"Enter coefficient and exponent for term {i+1}: ").split())
new_node = Node(coefficient, exponent)
if polynomial is None:
polynomial = new_node
new_node.next = new_node
else:
temp = polynomial
while temp.next != polynomial:
temp = temp.next
temp.next = new_node
new_node.next = polynomial
return polynomial

def add_polynomials(poly1, poly2):


result = None
temp1 = poly1
temp2 = poly2

while temp1 and temp2:


if temp1.exponent > temp2.exponent:
new_node = Node(temp1.coefficient, temp1.exponent)
new_node.next = result
result = new_node
temp1 = temp1.next
elif temp1.exponent < temp2.exponent:
new_node = Node(temp2.coefficient, temp2.exponent)
new_node.next = result
result = new_node
temp2 = temp2.next
else:
sum_coefficient = temp1.coefficient + temp2.coefficient
if sum_coefficient != 0:
new_node = Node(sum_coefficient, temp1.exponent)
new_node.next = result
result = new_node
temp1 = temp1.next
temp2 = temp2.next

while temp1:
new_node = Node(temp1.coefficient, temp1.exponent)
new_node.next = result
result = new_node
temp1 = temp1.next
while temp2:
new_node = Node(temp2.coefficient, temp2.exponent)
new_node.next = result
result = new_node
temp2 = temp2.next

return result

def print_polynomial(polynomial):
temp = polynomial
while True:
print(f"{temp.coefficient}x^{temp.exponent} + ", end="")
temp = temp.next
if temp == polynomial:
break
print("0")

def main():
terms1 = int(input("Enter the number of terms in the first polynomial: "))
poly1 = create_polynomial(terms1)
terms2 = int(input("Enter the number of terms in the second polynomial: "))
poly2 = create_polynomial(terms2)

print("First polynomial:")
print_polynomial(poly1)
print("Second polynomial:")
print_polynomial(poly2)

result = add_polynomials(poly1, poly2)


print("Sum of polynomials:")
print_polynomial(result)

if __name__ == "__main__":
main()

//OUTPUT:>

You might also like