Number of occurrences of a number in a list

Question:

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)
Asked By: Murshida Mouree

||

Answers:

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.

Answered By: Michael Cao

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.

Answered By: kaliiiiiiiii

There are three cases in this recursion:

  1. The list is empty
  2. The popped item is the value you are counting
  3. 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
Answered By: thomaoc
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.