我有一個練習,我需要在串列中找到一個數字第一次出現的索引。但是None如果找不到索引,我也需要回傳,這意味著該數字不在串列中。我需要用 Python 中的遞回函式來做到這一點。
我已經創建了一個代碼:“找到串列中第一次出現數字的索引”。它有效。
def index(lst, number_find):
if lst == []:
return None
elif lst[0] == number_find:
return 0
else:
return 1 index(lst[1:], number_find)
liste = range(51)
print(index(liste, 42))
但是如果數字不在串列中,我就無法撰寫管理案例的代碼。我已經這樣做了:
def index(lst, number_find):
if number_find not in lst:
return None
elif lst == []:
return None
elif lst[0] == number_find:
return 0
else:
return 1 index(lst[1:], number_find)
liste = range(51)
print(index(liste, 42))
但是在這里使用“not in”對我來說并不好,因為這似乎使用了一些我無法使用的迭代代碼。
uj5u.com熱心網友回復:
您必須防止None從遞回呼叫回傳的情況,因為1 None會引發TypeError:
def index(lst, number_find):
if lst == []:
return None
elif lst[0] == number_find:
return 0
else:
i = index(lst[1:], number_find)
if i is not None:
return 1 i
return None # not strictly necessary as None returned implicity
當然,當你從每個if-block回傳時,你可以省略 any else。此外,None是默認回傳值,因此您可以縮短邏輯
def index(lst, number_find):
if lst:
if lst[0] == number_find:
return 0
if (i := index(lst[1:], number_find)) is not None:
return 1 i
順便說一句,由于切片在O(N)這里,所有這些方法都是二次的。所以這是一個具有線性復雜度的解決方案:
def index(lst, number_find):
def rec(it, i=0):
if (n := next(it, None)) is not None:
return i if n == number_find else rec(it, i 1)
return rec(iter(lst))
uj5u.com熱心網友回復:
user2390182 接受的答案詳細解釋了如何處理None遞回呼叫回傳的可能值。
另一種方法是以尾遞回方式撰寫函式:
def index(lst, number_find, acc=0):
if lst == []:
return None
elif lst[0] == number_find:
return acc
else:
return index(lst[1:], number_find, acc 1)
請注意,python 不執行 tail-rec 優化;但這種方法仍然避免了這個1 None問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/326815.html
上一篇:根據id遞回獲取樹段
