你的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