Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Number of occurrences of a number in a list

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading