# Bug in: Practice Makes Perfect 11/15 (count)?

#1

This exercise seems to be a little buggy.

code:

def count(xs, item):
----if( len(xs) == 0 ):
--------return 0
----elif( xs.pop(0) == item ):
--------return 1 + count(xs, item)
----else:
--------return count(xs, item)

+++++++++++++++++++++++++

Oops, try again. Your function fails on count([],5). It returns 1 when it should return 0.

+++++++++++++++++++++++++++

Testing on my own interpreter returns 0 as supposed

#2

Hi, @kokke,

You have posted an interesting recursive solution. As given, it does produce the correct output, so Codecademy's message does not clearly describe the actual problem.

Your `count` function changes the contents of the list that is passed to it. Test the function by assigning a list to a variable, and then calling the function twice to see what happens, as follows ...

``````nums = [2, 5, 2, 2, 5]
print count(nums, 5)
print count(nums, 2)``````

Output ...

``````2
0``````

The second call returned `0`, when, if the original list had been left intact, it would have returned `3`.

Following is a suggested revision, which is still recursive, but works with a copy of the original list, so that the original is left intact ...

``````def count(a_list, item):
xs = a_list[:]
if(len(xs) == 0 ):
return 0
elif( xs.pop(0) == item ):
return 1 + count(xs, item)
else:
return count(xs, item)

nums = [2, 5, 2, 2, 5]
print count(nums, 5)
print count(nums, 2)``````

Output ...

``````2
3``````

#3
``````def count(sequence,item):
amount = 0
for n in sequence:
if n == item:
amount += 1
return amount``````