Program to calculate the sum of polynomials

Click For Summary
SUMMARY

This discussion focuses on creating a Python function to calculate the sum of two polynomials represented as dictionaries, where keys are powers and values are coefficients. The initial implementation only sums coefficients for matching powers, which is insufficient for general cases. The solution involves iterating over the union of keys from both polynomial dictionaries and using the `get` method to handle missing powers gracefully. The final approach ensures that all powers are considered, resulting in a correct polynomial sum.

PREREQUISITES
  • Understanding of polynomial representation in programming
  • Familiarity with Python dictionaries and their methods
  • Knowledge of basic control flow in Python (loops, conditionals)
  • Experience with set operations in Python
NEXT STEPS
  • Learn about Python dictionary methods, specifically `get()`
  • Explore set operations in Python for combining keys
  • Study polynomial arithmetic and its applications in programming
  • Investigate optimization techniques for polynomial operations in Python
USEFUL FOR

Python developers, computer science students, and anyone interested in mathematical programming and polynomial manipulation.

mathmari
Gold Member
MHB
Messages
4,984
Reaction score
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
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)
 
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:
 
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. 🤔
 
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 ·
Replies
5
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 178 ·
6
Replies
178
Views
9K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 13 ·
Replies
13
Views
2K