pythonheadache
pythonheadache

Reputation: 106

Recursive Python function to count occurrences of an element in a list

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'))

Upvotes: 2

Views: 13893

Answers (4)

Tanveer Alam
Tanveer Alam

Reputation: 5275

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

Upvotes: 2

jme
jme

Reputation: 20765

Taking advantage of the fact that True == 1 and False == 0:

def count(x, t):
    if not x:
        return 0
    else:
        return (x[0] == t) + count(x[1:], t)

Though I might honestly prefer the selected answer over this, as it's more explicit.

Upvotes: 1

saarrrr
saarrrr

Reputation: 2897

You don't need recursion for this.

print ['a','b','c','b','b','d'].count('b') #prints 3

Upvotes: 0

Freestyle076
Freestyle076

Reputation: 1556

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

Upvotes: 2

Related Questions