# L-14 MCS 275 Fri 15 Feb 2008 : facstack.py

# We construct the stack of function calls
# for a recursive computation of factorials.

def F(n):
   """
   Returns the n-th factorial.
   """
   if n <= 0: 
      return 1 
   else: 
      return n*F(n-1)
  
def facstack(n):
   """
   Builds the stack of function calls in
   a recursion for the factorial of n.
   """
   S = []
   S.insert(0,'F(%d)' % n)
   while S != []:
      print 'S =', S
      e = S.pop(0)
      n = eval(e[2:len(e)-1])
      if n <= 1:
         result = 1
         while S != []:
            e = S.pop(0)
            n = eval(e[2:len(e)-1])
            result = result * n  
      else:
         S.insert(0,'F(%d)' % n)
         S.insert(0,'F(%d)' % (n-1))
   return result

def main():
   """
   Prompts the user for a number and a
   stack to evaluate the factorial.
   """
   n = input('give n : ')
   f = facstack(n)
   print 'F(%d) = %d' % (n,f), f == F(n)

main()
