Is it possible to remove recursion from this function?

前端 未结 3 609
忘了有多久
忘了有多久 2021-01-20 01:26

I have been playing with this a while, and just cannot see an obvious solution. I want to remove the recursion from the XinY_Go function.

def XinY_Go(x,y,ind         


        
3条回答
  •  天涯浪人
    2021-01-20 02:05

    Everything we think of as recursion can also be thought of as a stack-based problem, where the recursive function just uses the program's call stack rather than creating a separate stack. That means any recursive function can be re-written using a stack instead.

    I don't know python well enough to give you an implementation, but that should point you in the right direction. But in a nutshell, push the initial arguments for the function onto the stack and add a loop that runs as long as the size of the stack is greater than zero. Pop once per loop iteration, push every time the function currently calls itself.

提交回复
热议问题