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

How do you count the number of negative items in a list using a recursive function?

I have to make a recursive function that counts how many negative values there are in a given list, but I can’t figure out what I am supposed to return for each conditional.

def countNegatives(list):
    """Takes in a list of numbers and
    returns the number of negative numbers
    that are inside the list."""
    count = 0
    if len(list) == 0:
        return 0
    else:
        if list[0] < 0:
            return count + 1
        else:
            return countNegatives(list[1:])

print(countNegatives([0, 1, -1, 3, -5, 6])) # should output 2 but gives me 1
print(countNegatives([-1, -3, 50,-4, -5, 1])) #should output 4 but gives me 1

>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

The problem with your code is that you are not keeping track of the running count of negative numbers in the recursive calls. Specifically, you are returning count + 1 when the first item of the list is negative, and discarding the rest of the list, instead of using a recursive call to count the number of negative items in the rest of the list.

To fix the problem, you can add the result of the recursive call to count in both cases, when the first item is negative and when it is not. This way, the running count of negative items will be accumulated through the recursive calls, and returned as the final result when the base case is reached.

Here’s a corrected version of your code:

def countNegatives(lst):
    """Takes in a list of numbers and
    returns the number of negative numbers
    that are inside the list."""
    count = 0
    if len(lst) == 0:
        return 0
    else:
        if lst[0] < 0:
            count += 1
        count += countNegatives(lst[1:])
        return count

print(countNegatives([0, 1, -1, 3, -5, 6]))  # Output: 2
print(countNegatives([-1, -3, 50, -4, -5, 1]))  # Output: 4

Note that I renamed the parameter list to lst, because list is the name of a built-in Python data type, and it is a good practice to avoid using built-in names as variable names.

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