Recursive Python function to count occurrences of an element in a list
10,936
Solution 1
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
Base case: empty list, there are no keys in the list
1st case: first element matches the key, count it (1) and recursive call on all but firsst element
2nd case: first element doesn't match, don't count it (0) and recursive call on all but first element
Solution 2
def element_count(input_list, ele, count=0):
if ele in input_list:
count = count + 1
input_list.remove(ele)
return element_count(input_list, ele, count)
else:
return count
input_list = ['a','b','c','b','b','d']
print "Count of 'b' in input list is :", element_count(input_list, 'b')
print "Count of 'a' in input list is :", element_count(input_list, 'a')
Gives count result
as:
Count of 'b' in input list is : 3
Count of 'a' in input list is : 1
Author by
pythonheadache
Updated on June 14, 2022Comments
-
pythonheadache almost 2 years
How do I do a recursive function that tells me how many time an element exists in a list. As an example lets say I have the following list ['a','b','c','b','b','d']. How do I do a recursive function that takes 2 arguments. One being the list and the other the element. The function has to return the number of times the element is present in the list.
I tried the following but position gets restarted everytime we go back in the function:
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'))
-
pythonheadache over 9 yearsThank you, its just I don't understand how is it verifying the 2nd element and 3rd element and so forth with lst[1:] , key
-
Freestyle076 over 9 yearslst[1:] expresses the subset of the original list from [1:len(lst)]. This is everything but the first element in the list. Thus we one by one travel down the list, looking at the first element each time. The recursive calls take a list that is one smaller each time, i.e. checking the next element
-
jme over 9 yearsRather than writing
if lst == []: return 0
, one should writeif not lst: return 0
. It's more pythonic, and it allows for the user to input, for instance, a tuple instead of a list. -
nbro over 9 yearsThe OP is asking specifically for a recursion algorithm.