Recursion Limit with Python?

倾然丶 夕夏残阳落幕 提交于 2021-01-27 20:09:47

问题


I have a program written recursively which, due to its nature, will fluctuate dramatically and thus, go over Python's limit. The shape of the program is also quite important, so I'd rather not change that.

I've come across increasing the recursion limit like so:

sys.setrecursionlimit(1500)  

My question is whether or not it is advisable in my situation to increase the recursion limit like this? I've seen people advise against it for numerous reasons.


回答1:


sys.setrecursionlimit(1500) 

is perfectly fine for increasing recursion depth.(within reason!) You've posted no code, though if there is "wild fluctuations", this is not a stable solution. Python by-and-large should not be used for deep recursion. It seems to me that you have 3 options: 1. De-construct your function and do things iteratively, as opposed to recursion.

If you have your heart truly set on recursion: 2. Use Java recursively 3. Use C++ recursively




回答2:


Not a solution, per se, but you might be able to leverage the functools.lru_cache function decorator to memoize your recursive function and prevent it from running to full depth.

Without any insight into what you're doing, it's tough to know if this will be possible. If it's just a simple recursive mathematical function (e.g. Fibonacci numbers), you might have some luck with this approach.

The advantage is that you don't have to make any structural changes to your code--just add @lru_cache(maxsize=None) at the top of your function definition.



来源:https://stackoverflow.com/questions/45869066/recursion-limit-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!