# L-17 MCS 275 Fri 17 Feb 2017 : facstack.py

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

def fac(nbr):
    """
    Returns the factorial of the number nbr.
    """
    if nbr <= 0:
        return 1
    else:
        return nbr*fac(nbr-1)

def facstack(nbr):
    """
    Builds the stack of function calls in
    a recursion for the factorial of nbr.
    """
    from ast import literal_eval
    stk = ['F(%d)' % nbr]
    while stk != []:
        print('S =', stk)
        exp = stk.pop(0)
        nbr = literal_eval(exp[2:len(exp)-1])
        if nbr <= 1:
            result = 1
            while stk != []:
                exp = stk.pop(0)
                nbr = literal_eval(exp[2:len(exp)-1])
                result = result * nbr
        else:
            stk.insert(0, 'F(%d)' % nbr)
            stk.insert(0, 'F(%d)' % (nbr-1))
    return result

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

if __name__ == "__main__":
    main()
