- #1

mathmari

Gold Member

MHB

- 5,049

- 7

A polynomial can be represented by a dictionary by setting the powers as keys and the coefficients as values. For example $x^12+4x^5-7x^2-1$ can be represented by the dictionary as $\{0 : -1, 2 : -7, 5 : 4, 12 : 1\}$. Write a function in Python that has as arguments two polynomials in dictionary representation and returns the dictionary that represent the sum of the polynomials.

I wrote the following program :

Code:

```
def add_poly(P1, p2) :
p3 = {}
for key in p1:
if key in p2:
sum_pol = p1[key]+p2[key]
p3[key] = sum_pol
return p3
p1 = {0:-1, 2:-7, 5:4, 12:1}
p2 = {0:2, 2:5, 5:2, 12:3}
print(add_poly(p1,p2))
```

But this works only if the given polynomials have the same powers, right?

What can we change to consider the general case?

I thought to do something like :

Code:

```
def add_poly(p1, p2) :
pol = {}
key = 0
x = True
while x == True :
if key in p1 and key in p2:
sum_pol = p1[key]+p2[key]
pol['key'] = sum_pol
elif key in p1 :
sum_pol = p1[key]
pol['key'] = sum_pol
elif key in p2 :
sum_pol = p2[key]
pol['key'] = sum_pol
elif key > len(p1) and key > len(p2) :
x = False
else :
pass
key += 1
return pol
p1 = {0:-1, 2:-7, 5:4, 12:1}
p2 = {0:2, 2:5, 3:2, 12:3}
print(add_poly(p1,p2))
```

But this doesn't work correctly.

:unsure: