Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I'm trying to make the program that returns the 3-tuple containing a number of negative values in nums, each number of zero values in nums, and a number of positive values in the nums.

This is my attempt but it seems not to accumulate the results.

def sign_counters(nums):

    """Returns the 3-tuple containing a number of negative values in nums, 

    a number of zero values in nums and a number of positive values in nums."""

    for num in nums:

        result1 = 0

        if num > 0:

            result1 += 1

        result2 = 0

        if num < 0:

            result2 += 1

        result3 = 0

        if num == 0:

            result3 += 1

    return result1, result2, result3

print(sign_counters([-1, 2, 0, -3, -1, 0]))

print(sign_counters([-1, -5, -3, -2]))

This should be an expected result with a test code (last two lines):

(3, 2, 1)

(4, 0, 0)

But my code comes up with this:

(0, 0, 1)

(0, 1, 0)

1 Answer

0 votes
by (36.8k points)

Every loop, it is a resetting result1, result2, and result3 to 0. Here's a better code:

def sign_counters(nums):

    """Returns a 3-tuple containing the number of negative values in nums, 

    the number of zero values in nums and the number of positive values in nums."""

    result1 = result2 = result3 = 0

    for num in nums:

        if num > 0:

            result1 += 1

        if num < 0:

            result2 += 1

        if num == 0:

            result3 += 1

    return result1, result2, result3

print(sign_counters([-1, 2, 0, -3, -1, 0]))

print(sign_counters([-1, -5, -3, -2]))

 Want to be a master in Data Science? Enroll in this Data Science Courses

Browse Categories

...