# L-24 MCS 507 Mon 17 Oct 2011 : enumpowersiterator.py

class PowerEnumerator:
   """
   Iterator class to enumerate
   exponents of all monomials 
   in n variables of degree d.
   """
   def __init__(self,n,d):
      """
      An enumerator for all powers
      in n variables of degree d.
      """
      accu = [0 for i in xrange(n)]
      self.stack = [(0,accu)]
      self.degree = d

   def next(self):
      """
      Returns the next power or None
      if at end of enumeration.
      """
      S = self.stack
      d = self.degree
      while True:
         if S == []: return None
         (k,accu) = S.pop(0)
         if sum(accu) == d:
            return accu
         elif k < len(accu):
            for i in xrange(d,-1,-1):
               new_accu = [x for x in accu]
               new_accu[k] = i
               S.append((k+1,new_accu))

def main():
   """
   Prompts the user for degree and number
   of variables and then prints all terms.
   """
   d = input('give degree : ')
   n = input('give number of variables : ')
   p = PowerEnumerator(n,d)
   while True:
      t = p.next()
      if t == None: break
      print t

if __name__=="__main__": main()
