Skip to content Skip to sidebar Skip to footer

Count Negative Values In A List Of Integers Using Python?

I am having problems with this CodingBat question: Given a list of integers, return the count of the negative values. count_negative([-1, -2, -3]) → 3 count_negative([2, 2, 2,

Solution 1:

You are setting total back to zero after every loop. Put it outside the loop:

Also, the function will break after the first loop, because after a function returns something it breaks. Also put return total outside of the loop:

total = 0for value in list:
    total += value
return total

I don't see how this will determine whether a number is a negative or not. You can use an if-statement inside of your loop.

if value < 0:
    total += 1

Or you can just use a list comprehension:

sum(1 for i in lst if i < 0)

By the way, never name something list. It overrides the built-in. I'm rather surprised your question did it.

Solution 2:

Turn it into a pd.DataFrame then use df[df>0].count()/len(df)

Post a Comment for "Count Negative Values In A List Of Integers Using Python?"