4

For instance, this is my factorial function:

def fact(n):
    if n<=1: return 1
    else: return n*fact(n-1)

But it crashes when n is too high. I'd like to emulate this exact same function using a stack emulation. How would I do something like this? What if it's not tail-recursive? Having a hard time finding explanations.

1 Answer 1

4

First off, you could make it tail recursive:

def tfact(n,acc=1):
    if n<=1: return acc
    else: return tfact(n-1,acc*n)

But for a more direct translation:

def ifact(n):
    stack = []
    while True:
        if n==1:
            while stack:
                n *= stack.pop()
            break
        else:
            stack.append(n)
            n -= 1
    return n 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.