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

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

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

def main():
   """
   Prompts the user for the number of variables
   and the number of terms wanted.
   """
   n = input('give number of variables : ')
   m = input('how many terms do you want ? ')
   p = PowerEnumerator(n)
   for i in xrange(m): print p.next()

if __name__=="__main__": main()
