python - 用于计算列表中元素出现次数的递归 Python 函数

标签 python recursion

如何执行一个递归函数来告诉我某个元素在列表中存在的次数。举个例子,假设我有以下列表 ['a','b','c','b','b','d']。如何执行带有 2 个参数的递归函数。一个是列表,另一个是元素。该函数必须返回该元素在列表中出现的次数。

我尝试了以下操作,但每次我们返回函数时位置都会重新启动:

def number_of_repetitions(liste, element):


    position = 0
    number_of_rep = 0


    if position == len(liste)-1:
        return number_of_rep

    if liste[position] == element:
        position +=1
        return number_of_rep + number_of_repetitions(liste[position], element)
    else:
        position +=1
        return number_of_rep + number_of_repetitions(liste[position], element)

print(number_of_repetitions(['a','b','c','b'],'b'))

最佳答案

def recursiveCount(lst,key):
    if lst == []: #base case
        return 0
    if lst[0] == key:
        return 1 + recursiveCount(lst[1:],key)
    else:
        return 0 + recursiveCount(lst[1:],key)

print recursiveCount(['a','b','a'],'a') #prints 2

基本情况:空列表,列表中没有键

第一种情况:第一个元素与键匹配,对其进行计数(1)并对除第一个元素之外的所有元素进行递归调用

第二种情况:第一个元素不匹配,不计算它(0)并递归调用除第一个元素之外的所有元素

关于python - 用于计算列表中元素出现次数的递归 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27466350/

相关文章:

Python - 对数组列表进行分类第 2 部分

python - 错误: 'tuple' is not callable in python 3

python - 为什么 Python 教程说列表理解比 map() 更灵活?

python - 获取网站上 javascript 重定向的最终目的地

c# - 找到最低的子文件夹并压缩它们

perl - 如何在 Perl 中设置硬最大递归深度?

python - Psycopg2 使用占位符插入表格

c++ - 所有带有 "recursion"的 child 的静态变量

algorithm - 阶乘时间复杂度算法是否需要递归或堆栈?

c++ - 这是使用递归的正确方法吗?