title: Problems in summing two polynomials using python
body: <p>I'm asked to make a program that calculates the addition of two polynomials of n and m degrees. I made two dictionaries (one for the first polynomial and the other is for the other polynomial) since each one has the coefficients as values and degrees as keys so that I can check whether the keys from both dictionaries are identical, then I can sum their values. But I don't know why I always get an error. My code so far is:</p>
  
  <pre><code>class poly:
      def __init__(self, L=[], D=[]):
         self.coef=L
         self.deg=D
  
      def __add__(self,L2):
         if len(self.coef)&gt;len(self.deg):
            dec=dict(zip(self.deg,self.coef))
            dec[0]=self.coef[-1]
  
         else:
            dec=dict(zip(self.deg,self.coef))
  
         Dec1=dec
  
         if len(L2.coef)&gt;len(L2.deg):
            dec=dict(zip(L2.deg,L2.coef))
            dec[0]=L2.coef[-1]
         else:
            dec=dict(zip(L2.deg,L2.coef))
  
         Dec2=dec
         p=[]
  
         if len(Dec2)&gt;len(Dec1):
            for i in Dec2:
              if i in Dec1:
                  s=Dec1[i]+Dec2[i]
                  p=p+[s]
              else:
                  p=p+p[Dec2[i]]
  
            for x in Dec1:
              if x in Dec2:
                  p=p
              else:
                  p=p+[dec1[x]]
         return(poly(p))
  
         if len(Dec2)&lt;len(Dec1):
           for x in Dec1:
               if x in Dec2:
                  g=Dec1[x]
                  p=p+[g]
               else:
                  p=p+[Dec1[x]]
  
           for m in Dec2:
              if m in Dec1:
                  p=p
              else:
                  p=p+[Dec2[m]]
         return (poly(p))
  </code></pre>
  
  <p>This code doesn't work for all my examples such as </p>
  
  <pre><code>&gt;&gt;&gt; p=poly([2,4,7,34],[6,4,2])
  &gt;&gt;&gt; p1=poly([6,3,7,2,8],[8,4,2,1])
  &gt;&gt;&gt; p2=p+p1
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
      p2=p+p1
    File "poly.py", line 31, in __add__
      p=p+p[Dec2[i]]
  IndexError: list index out of range
  &gt;&gt;&gt; #The numbers in the first list is the coefficients and the second list is for degrees
  </code></pre>
  
  <p>This doesn't work! But it worked when I've done the addition without using class method. I'm a beginner and I did my best to fix the problem. </p>
  
  <p>Another question is how to write the def <strong>str</strong> for my code? I really don't have any idea what I should write in the beginning. I'm sorry guys but I'm new in programming and I need an easy code such as mine.</p>