MHB Program to calculate the sum of polynomials

AI Thread Summary
A polynomial can be represented as a dictionary with powers as keys and coefficients as values, such as $x^{12}+4x^{5}-7x^{2}-1$ represented as {0: -1, 2: -7, 5: 4, 12: 1}. A Python function is needed to sum two polynomials in this format. The initial implementation only works for polynomials with the same powers, prompting a discussion on how to handle the general case.To improve the function, it's suggested to iterate over the union of the keys from both polynomial dictionaries. This allows for the inclusion of all powers present in either polynomial. Instead of checking each key's existence with multiple if statements, the use of `get(key, 0)` simplifies the process by returning the coefficient or zero if the key is absent. This approach streamlines the addition of coefficients for each power, ensuring that all terms are accounted for in the final result.
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)`. 🤔
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...

Similar threads

Replies
5
Views
3K
Replies
3
Views
2K
Replies
1
Views
1K
Replies
1
Views
1K
Replies
5
Views
2K
Replies
6
Views
1K
Back
Top