我要编写一个程序来查找list/srting中特定元素的所有索引数,我必须使用递归,而我的func只能得到2个参数。在
我的问题是我的程序只找到第一个索引并停止,我如何处理它?在
我的代码:
def find_all(L, v):
return 0 if L[0] == v else 1 + find_all(L[1:], v)
输入:
1find_all( [1,2,3,4,2,4,5,2,1], 2)
2find_all("hello wonderful world", "w")
输出:
1[1,4,7]
2。[6,16]
Tags:
你得设法跟踪柜台。其思想是使用
find_all(L, v)
作为“实际”递归函数的接口:考虑到这是家庭作业,我不会为你做这项工作,但你应该可以从这里继续下去。在
您可以使用Pythons功能向后遍历列表并获取最后一个元素。然后用+运算符将列表放在一起。通过向后查看列表,您可以在找到某个值时找到标记,而不是在从列表的开始移动到末尾时丢失它。在
相关问题 更多 >
编程相关推荐