如何执行一个递归函数来告诉我某个元素在列表中存在的次数。举个例子,假设我有以下列表 ['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/