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)
CodePudding user response:
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.
CodePudding user response:
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.
CodePudding user response:
There are three cases in this recursion:
- The list is empty
- The popped item is the value you are counting
- The popped item is not the value you are counting
You have treated the first two cases, but not the third.
def count_x( items, x ):
if items==[]:
return 0
first = items.pop(0)
if first == x:
return 1 count_x(items, x)
return count_x(items, x) # Fix