Reputation: 3
This program below is supposed to count the number of occurrences of x in a list. Can not identify the error in the code
def count_x( items, x ):
if items==[]:
return 0
first = items.pop(0)
if first == x:
return 1 + count_x(items, x)
Upvotes: 0
Views: 62
Reputation: 3609
There are better ways to do this, but it's worth addressing why your code is throwing an error.
You don't have a case for when the item popped is not equal to your search item. This causes the function to return a None. Since it is working recursively, it tries to compute int + None
, which leads to an error.
The other issue is that you are modifying the list with the function, which you may not want. For example:
def count_x( items, x ):
print(items)
if items==[]:
return 0
first = items.pop(0)
if first == x:
return 1 + count_x(items, x)
else:
return count_x(items, x)
items = [1, 2, 1, 1]
print(count_x(items, 1))
print(items)
Your items
will become an empty list after you run the function.
Upvotes: 2
Reputation: 1135
I think it should work as following:
def count_x(items:list, x ):
count = 0
for item in items:
if item == x:
count = count + 1
return count
count = count_x(items, x)
You could also simply use count = items.count(x)
tho.
Upvotes: 0