使用递归查找所有索引

2024-09-28 03:14:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我要编写一个程序来查找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: 代码程序元素hello参数returnifdef
3条回答
C++中的代码>
 int allIndexes(int input[], int size, int x, int output[]){

 if(size==0)
      return 0;
    int ans=allIndexes(input, size-1, x , output );
    if(input[size-1]==x)
    {
        output[ans]=size-1;
       return ans+1; 
    }
    return ans;
}  

你得设法跟踪柜台。其思想是使用find_all(L, v)作为“实际”递归函数的接口:

def find_all(L, v):
    return _find_all(L, v, 0)

def _find_all(L, v, position):
    # Your algorithm here

考虑到这是家庭作业,我不会为你做这项工作,但你应该可以从这里继续下去。在

您可以使用Pythons功能向后遍历列表并获取最后一个元素。然后用+运算符将列表放在一起。通过向后查看列表,您可以在找到某个值时找到标记,而不是在从列表的开始移动到末尾时丢失它。在

def find_all(L, v):
    if not L:
            return []

    result = []
    if L[-1] == v:
            result = [len(L)-1]

    return find_all(L[:-1], v) + result

相关问题 更多 >

    热门问题