Program to calculate the sum of polynomials

  • #1
mathmari
Gold Member
MHB
5,049
7
Hey! 😊

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:
 
Technology news on Phys.org
  • #2
Hey mathmari!

I can do:
Code:
python
>>> len({0:-1, 2:-7, 5:4, 12:1})
4

But 4 is not the highest power is it? (Worried)
 
  • #3
Klaas van Aarsen said:
I can do:
Code:
python
>>> len({0:-1, 2:-7, 5:4, 12:1})
4

But 4 is not the highest power is it? (Worried)

So is the part

Code:
elif key > len(p1) and key > len(p2) :
            x = False

wrong? :unsure:
 
  • #4
mathmari said:
So is the part
elif key > len(p1) and key > len(p2) : x = False
wrong?
Indeed. Instead we need to check if the key is greater than the greatest key in both p1 and p2. 🤔
 
  • #5
We can use `max(p1)` to find the highest power in `p1`. 🤔

But basically we want to iterate over the set that both polynomials have in common.
We can construct it with `set().union(p1.keys(), p2.keys())`.
Then we can do `for power in set().union(p1.keys(), p2.keys()): ...`. 🤔

Additionally, we can do `p1.get(key, 0)` to get the power if there is one, or 0 otherwise.
Then we don't have to use if statements, but we can just do `p1.get(key, 0) + p2.get(key, 0)`. 🤔
 

Similar threads

Replies
5
Views
2K
Replies
3
Views
2K
Replies
178
Views
4K
Replies
1
Views
1K
Replies
5
Views
2K
Replies
6
Views
1K
Replies
7
Views
2K
Back
Top