编写一个函数,返回数据中第一次出现值的下标或None USING RECURSION ONLY



我被要求:

编写一个函数find(data,value(,返回数据中第一次出现值的下标,如果找不到值,则返回None。函数不能使用循环或列表综合,也不能使用列表的索引方法。只能使用递归!

这是我当前的代码:

def find(data, value):
"""Returns the subscript of the first occurrence of value in data or None"""
if not data:
return None
if data[0] == value:
return data[value]
return find(data[1:], value)
Test code:
print(find([10, 20, 30], 0))
---> None
print(find(["hi", "there", "you"], "there"))
---> 1

我很难弄清楚如何在找到值时返回数据中第一次出现的值的索引!

从两个基本情况开始:一个是空列表,另一个是匹配第一个元素。

对于空列表:只需返回None

如果第一项匹配,则应返回0

现在递归将只是1 + recursive_function。问题是,您需要注意递归函数返回None的情况。这可能看起来像:

def find(data, value):
"""Returns the subscript of the first occurrence of value in data or None"""
if not data:
return None
if data[0] == value:
return 0
n = find(data[1:], value)
if n is not None:
return 1 + n 
return None
print(find([10, 20, 30], 0))
#---> None
print(find(["hi", "there", "you", "there"], 'there'))
#---> 1

如果你可以使用函数签名,你可以通过在一个以默认值零开始的参数中跟踪当前索引来简化它:

def find(data, value, i=0):
"""Returns the subscript of the first occurrence of value in data or None"""
if not data:
return None
if data[0] == value:
return i

return find(data[1:], value, i+1)
print(find([10, 20, 30], 0))
#---> None
print(find(["hi", "there", "you", "there"], 'there'))
#---> 1

下面是一个例子不是函数的"种子"值为-1表示计数,然后每次递归都会更新计数。

def first_index_recursive(l: list, item, count = -1) -> int:
"""
return the index of the first element of the list that
matches the item. If no match, return -1
>>> first_index_recursive([34, 43, 3, 78, 1], 3)
2
>>> first_index_recursive([34, 43, 3, 78, 1], 99)
-1
>>> first_index_recursive([34], 34)
0
>>> first_index_recursive([], 99)
-1
>>> first_index_recursive([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 14)
14
"""
# original list was empty, or we didn't find it
if len(l) < 1:
return -1
# each time we recurse, count increases by 1 and points to the current
# index of the original list
count += 1
# found it
if l.pop(0) == item:
return count
# did not find it yet. recurse.
return first_index_recursive(l, item, count)
# for testing of function
if __name__ == "__main__":
import doctest
doctest.testmod()

最新更新