Count negative values in a list of integers using Python?

前端 未结 2 1764
遥遥无期
遥遥无期 2021-01-29 12:22

I am having problems with this CodingBat question:

Given a list of integers, return the count of the negative values.

count         


        
相关标签:
2条回答
  • 2021-01-29 12:45

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

    0 讨论(0)
  • 2021-01-29 13:08

    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 = 0
    for 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.

    0 讨论(0)
提交回复
热议问题