rosy
rosy

Reputation: 19

make a python code that counts negative numbers in each list?

I am trying to make a def count_neg() function that counts negative numbers in each list? Like this:

>>> count_neg ([[0, -1], [-2,-4],[5,5],[4,-4]])
[1,2,0,1]

I tried making it and came up with this but the output did not count for each list?

def count_neg(*args):
    for i in args:
        counter = 0
        for j in i:
            if j < 0:
                counter += 1 
    print(counter)

count_neg([3,-2,0],[-1,-4,3])

Upvotes: 1

Views: 310

Answers (4)

Muhammad
Muhammad

Reputation: 21

hi please use this code

def count_neg(*args):
    counter=[]
    for i in args:
        count=0
        for j in i:
            if j<0:
                count+=1
        if count>0:
            counter.append(count)     
    print(counter)

count_neg([3,-2,0],[-1,-4,3])

Upvotes: 0

lenik
lenik

Reputation: 23556

This works properly:

>>> def count_neg(*args):
...     result = []
...     for i in args:
...         counter = 0
...         for j in i:
...             if j < 0:
...                 counter += 1
...         result.append(counter)
...     return result
... 
>>> count_neg([3,-2,0],[-1,-4,3])
[1, 2]
>>> count_neg ([0, -1], [-2,-4],[5,5],[4,-4])
[1, 2, 0, 1]
>>> 

Upvotes: 0

Sanil Khurana
Sanil Khurana

Reputation: 1169

I assume from your question that you don't just want the total number of negative numbers in the 2D list but rather a list of the count of negative numbers in each inner list.

For that, you need to have a list of number of negative numbers that appear in the lists. The below solution would work fine -

def count_neg(*args):
    negative_counters = []
    for i in args:
        counter = 0
        for j in i:
            if j < 0:
                counter += 1 
        negative_counters.append(counter)
    print(negative_counters)

Upvotes: 0

Ajay Dabas
Ajay Dabas

Reputation: 1444

It's because of printing the counter at the wrong place. It should be inside of outer loop rather than at the end of function.

def count_neg(*args):
    for i in args:
        counter = 0
        for j in i:
            if j < 0:
                counter += 1 
        print(counter)

count_neg([0, -1], [-2,-4], [5,5], [4,-4])

Output

1
2
0
1

Upvotes: 2

Related Questions