我採取這樣Python的遞歸順序搜索:遞歸順序搜索沒有返回值
def search(list1,n,pos):
if n==list1[0]:
return pos
else:
if list1==[]:
return -1
else:
pos=pos+1
list1.pop(0)
return search(list1,n,pos)
def searchCall(n):
anylist=[1,2,3,4,5,6,7,8,9,10]
pos=0
search(anylist,n,pos)
def main():
i=searchCall(8)
print i
if __name__=="__main__":
main()
所以我要做的就是設法找到名單上的n個元素,並且在每個遞歸調用我彈出列表的第一個元素,再次用剩下的列表調用搜索。問題是,當我把這個:
if n==list1[0]:
print pos
它打印在元素被發現的位置,但是當我改變了:
return pos
它打印無
也該元素時沒有發現它應該返回-1,而是顯示此錯誤消息:
if n==list1[0]:
IndexError: list index out of range
任何幫助嗎?
感謝