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

# We construct the stack of function calls
# of a recursion for Fibonacci numbers.

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

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

main()
