2017-04-24 67 views
0

Python代碼遞歸誤差在Python功能

def find(*num): 
    i =0 
    if num[i] != None: 
     print(num[i]) 
     return find(i+1) 

結果

RecursionError: maximum recursion depth exceeded in comparison 

如何停止在指數結束了嗎?

+1

你的代碼假設要做什麼?在列表中搜索?請發佈預期的輸入輸出 –

+0

歡迎來到SO!請閱讀此[如何問](http://stackoverflow.com/help/how-to-ask)以改善您的問題。 – thewaywewere

回答

0

當你的列表是50個元素或更長時,你的函數會拋出RecursionError,因爲這是python中的默認遞歸深度。此外,如果您的列表短於50個元素,它將拋出IndexError,因爲您沒有設置結束列表條件。 如果你想打印在列表中的所有數字元素,你可以使用一個循環:

def find (*num): 
    for entry in num: 
     if entry is not None: 
      print (entry) 

如果你確實想要一個遞歸解決方案,那麼你需要修改遞歸深度和國土資源使用和添加退出條件:

import resource, sys 
//be wary, your memory usage could went waaay up 
resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1)) 
sys.setrecursionlimit(10**6) 

def find (*num): 
    if len(num)==0: 
     return None 
    current, tail = num[0], num[1:] 
    if current is not None: 
     print (current) 
    find (tail) 
+0

Thx !!!!!你很親切! –

0

它看起來像你試圖打印傳遞給函數的最後一個(位置)參數的值。

這應該工作:

def find(*num): 
    print(num[-1]) 
0

你有錯誤結束了,因爲你沒有設置「遞歸結束」狀態。基本上你要添加的東西是這樣的:

def find(*nums): 
    if <your condition>: 
     return 

    ... logic ... 

很難說究竟應該在那裏,因爲我不太明白你想要完成什麼。