你的API的設計是嚴重有缺陷的。
>>> False == 0
True
你的導師正在爲你設置驚喜。例如:
where = search(["non-foo", "not-foo"], "foo") # returns False
if where == 0:
print "foo is in pole position"
# but "foo" isn't even a candidate
使其在失敗時返回None
。試試這個:
>>> def search(alist, key, pos=None):
... if pos is None: pos = len(alist) - 1
... if pos < 0: return None
... if key == alist[pos]: return pos
... return search(alist, key, pos - 1)
...
>>> search([1,2,3], 4) # -> None
>>> search([1,2,3], 3)
2
>>> search([1,2,3], 2)
1
>>> search([1,2,3], 1)
0
>>> search([], 1) # -> None
>>>
此方法的其他功能:(1)向您介紹它可以用在一個局部變量會在非遞歸函數中使用的「隱藏」 ARGS的概念。 (2)避免所有字符串切片的成本。
=========================================
對於這裏@ inspectorG4dget的利益,是我@安文的回答重構:
def xsearch(l,key,idx=0):
if l: # checks if list exists
if l[0] == key: # base case - first index is key
return idx
s = xsearch(l[1:], key, (idx + 1)) # recursion
if s is not False:
return s
#### and if s is False, it falls through and returns False ####
#### so it can return s unconditionally! ####
return False # returns false if key not found
def ysearch(l,key,idx=0):
if l: # checks if list exists
if l[0] == key: # base case - first index is key
return idx
return ysearch(l[1:], key, (idx + 1)) # recursion
return False # returns false if key not found
#### above statement is better put closer to the `if` ####
def zsearch(l,key,idx=0):
if not l: # checks if list exists
return False
if l[0] == key: # base case - first index is key
return idx
return zsearch(l[1:], key, (idx + 1)) # recursion
需要指出的是,我不能使用內置的.index功能或在運營商。儘管沒有這些,我覺得我很接近。 – JMJY 2010-11-28 05:59:12
沒有看到此評論,您不能使用索引。但方法可能相似。試一試並在此發佈答案 – pyfunc 2010-11-28 06:07:34
請確保你的老師知道:(a)當這個列表發生了足夠長的列表時,你仍然通過(b)重要的遞歸類最好以支持它的語言教授。如果說教練試圖讓你使用二傳手或者吸引者,給他/她肯定,但是沒有毀滅性的打擊腦袋,並且告訴他們這是來自aaronasterling。 – aaronasterling 2010-11-28 06:15:28