例如,寫在圖表的一些算法時像有沒有辦法在Python中進行無限深度的遞歸方法?
def f(graph):
#graph is dictionary of pairs vertex_i:{set of edges (i,j)} for 1<=i,j<=n
def g(vertex):
for vertex1 in graph:
do sth
...
for (i,j) in graph[vertex1]:
...
g(j)#recursive call
...
return ...
return g(1)
有限遞歸的深度有時是很煩人的,因爲代碼變得更長,更復雜,如果你要避免遞歸。 有沒有辦法達到無限的深度? 也許你可以描述在下面的方法
def nthNumber(n):
if n==1: return 1
else: return nthNumber(n-1)+1
(我知道這是簡單的愚蠢的,請不要放棄,如「你應該寫只是nthNumber(N)回答問題的你一般解決方案:迴歸n「 - 我對通用解決方案感興趣)。感謝幫助!
讓我換句話說:是否有可能用max來製造一個反覆的方法。深度10 ** 4或10 ** 5? – Antoine 2013-04-20 20:47:21
您可以將遞歸限制設置爲10 ** 4,但最終可能會崩潰python(它可能超過了安全限制 - 這取決於操作系統)。另外:http://stackoverflow.com/questions/2917210/python-what-is-the-hard-recursion-limit-for-linux-mac-and-windows – root 2013-04-20 20:52:19