Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of zeros in Python?

My code is currently written as:

convert = {0:0,1:1,2:2,3:3,4:0,5:1,6:2,7:1}
rows = [[convert[random.randint(0,7)] for _ in range(5)] for _ in range(5)]
numgood = 25 - rows.count(0)

print numgood
>> 25

It always comes out as 25, so it's not just that rows contains no 0's.

like image 452
derkyzer Avatar asked Jan 04 '14 05:01

derkyzer


People also ask

How do I count the number of zeros in Numpy?

You can use np. count_nonzero() or the np. where() functions to count zeros in a numpy array. In fact, you can use these functions to count values satisfying any given condition (for example, whether they are zero or not, or whether they are greater than some value or not, etc).

How do you count zeros in a string?

Loop through the characters of string and take the sum of all the characters. The sum of all the characters of the string will be the number of 1's, and the number of zeroes will be the (length of string - number of 1's).


2 Answers

Have you printed rows?

It's [[0, 1, 0, 0, 2], [1, 2, 0, 1, 2], [3, 1, 1, 1, 1], [1, 0, 0, 1, 0], [0, 3, 2, 0, 1]], so you have a nested list there.

If you want to count the number of 0's in those nested lists, you could try:

import random

convert = {0:0, 1:1, 2:2, 3:3, 4:0, 5:1, 6:2, 7:1}
rows = [[convert[random.randint(0, 7)] for _ in range(5)] for _ in range(5)]

numgood = 25 - sum(e.count(0) for e in rows)
print numgood

Output:

18
like image 119
Christian Tapia Avatar answered Oct 04 '22 18:10

Christian Tapia


rows doesn't contain any zeroes; it contains lists, not integers.

>>> row = [1,2,3]
>>> type(row)
<type 'list'>
>>> row.count(2)
1
>>> rows = [[1,2,3],[4,5,6]]
>>> rows.count(2)
0
>>> rows.count([1,2,3])
1

To count the number of zeroes in any of the lists in rows, you could use a generator expression:

>>> rows = [[1,2,3],[4,5,6], [0,0,8]]
>>> sum(x == 0 for row in rows for x in row)
2
like image 32
DSM Avatar answered Oct 04 '22 19:10

DSM