Python中的递归有多安全?
问题描述
我正在做一项 AI 作业,尽管我的教授提出了建议,但我无意用 lisp 写这个作业.但是,我确实想递归地编写它,以使其简洁明了.这是我的问题:
I'm working on an AI homework, and despite my professor's suggestions, I have no intention of writing this assignment in lisp. However, I do want to write it recursively, the better to keep it concise and simple. Here is my question:
如果我在大型状态空间上执行搜索,我是否会面临堆栈空间不足的重大风险?Python 堆栈有多深?
Am I running a major risk of running out of stack space if I perform a search over a large state space? How deep does the Python stack go?
解决方案
Python 堆栈有多深?
How deep does the Python stack go?
python 中默认的递归限制是 1000 帧.您可以使用 sys.setrecursionlimit(n)
来更改它,风险自负.
The default recursion limit in python is 1000 frames. You can use sys.setrecursionlimit(n)
to change that at your own risk.
如果您打算使用 python,我建议您使用更适合该语言的模式.如果您想使用递归样式搜索,并且需要任意堆栈深度,您可以利用 python 的增强生成器(协程)创建蹦床模式"(在 PEP342)
If you're set on using python, I would suggest using a pattern more suited to the language. If you want to use the recursive style search, and need arbitrary stack depth, you can make use of python's enhanced generators (coroutines) to create a "trampoline pattern" (there an example in PEP342)
尽管我的教授提出了建议,但我无意用 lisp 写这个作业
and despite my professor's suggestions, I have no intention of writing this assignment in lisp
如果该练习旨在基于递归,那么尾调用优化的语言(如 lisp)可能是您的最佳选择.
If the exercise is intended to be recursion-based, a tail-call optimized language, like a lisp, is probably your best bet.
相关文章