5

I need help doing a program which should receive ten numbers and return me the number of negative integers I typed.

Example:

If I enter:

1,2,-3,3,-7,5,4,-1,4,5

the program should return me 3.

How can I do it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael
  • 1,018
  • 4
  • 14
  • 30

3 Answers3

51

Break your problem down. Can you identify a way to check if a number is negative?

if number < 0:
    ...

Now, we have many numbers, so we loop over them:

for number in numbers:
    if number < 0:
        ...

So what do we want to do? Count them. So we do so:

count = 0
for number in numbers:
    if number < 0:
        count += 1

More optimally, this can be done very easily using a generator expression and the sum() built-in:

>>> numbers = [1, 2, -3, 3, -7, 5, 4, -1, 4, 5]
>>> sum(1 for number in numbers if number < 0)
3
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
31
sum(n < 0 for n in nums)

This is the most Pythonic way to do it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jamylak
  • 128,818
  • 30
  • 231
  • 230
2

Or you could use filter to "filter" out the negatives.

total = len(filter(lambda x: x < 0, my_list))

squiguy
  • 32,370
  • 6
  • 56
  • 63
  • 3
    Using `lambda` and `filter()` together is slower and less readable than a generator expression. – Gareth Latty Apr 13 '13 at 22:41
  • @Lattyware Well `filter` takes a `lambda`. I just like a functional approach :). I agree with you 100%. I even +1 your answer. – squiguy Apr 13 '13 at 22:45
  • `filter` takes a function - creating it using `lambda` is just useful in some cases. I was just commenting to say that this is generally a worse way to do this task. – Gareth Latty Apr 13 '13 at 22:54
  • most of the people behind python hate the use of `lamda`s, however they've gained a large following. I try to avoid them whenever possible. – jamylak Apr 14 '13 at 00:34
  • @jamylak Sure, just thought I would share a different way than putting up a duplicate answer. – squiguy Apr 14 '13 at 00:35
  • 1
    @squiguy you are also relying on `filter` building a `list` which wastes space and also means you have to add an enclosing call to `list(...)` under python 3 – jamylak Apr 14 '13 at 00:37
  • @squiguy The problem with this answer now is that a large portion of people use python 3 where this doesnt work unless you add `len(list(filter(lambda x: x < 0, my_list))` – jamylak Feb 14 '18 at 02:37