2

I am trying to get a loop which will tell me the number of 0 in a array of 50 random intergers from 0 to 2 (not including 2). And which will then calculate random integers again for the number of zeroes obtained.

I tried doing it but I am getting stuck at the primary stages and it is getting frustrating so any help would be much appreciated.

from numpy.random import randint

n = 50

R = randint(0,2,n)

for i in R:
    True = 0
    print array(True)

But it doesn't return an array and I don't know how to count the number of 0's as I can't use the len function as I normally would.

I tried using the while loop as well but ran into similar problems

5 Answers 5

4

Since your array contains only ones and zeroes, the count of zeroes will be obviously

num_zeroes = len(R) - sum(R)
Sign up to request clarification or add additional context in comments.

Comments

2

To count the 0s in R you can just do

sum(not n for n in R)

The advantage of this is that it will work even if you have numbers other than only 1s and 0s in the array.


Thanks to eryksun for pointing this out: you can also do

numpy.sum(R == 0)

2 Comments

Vectorized: numpy.sum(R == 0).
@user1778543 Sure - not n returns 1 if n is 0 and it returns 0 otherwise. not n for n in R: we loop over R and calculate not n for each element n, we then simply add these values with sum to obtain the total number of 0s.
0

Generating the array:

random_list = [random.randint(0,2) for x in xrange(50)]

number of 0's:

num_zeros = sum( 1 for x in random_list if x==0 )

generating the array again:

random_list = [random.randint(0,2) for x in xrange(num_zeros)]

Comments

0

Perhaps this is something you are looking for:

from numpy.random import randint

n = 50

R = randint(0,2,n)

def get_number_of_zeros(x):
    return sum(0 == ele for ele in x)

while(len(R) > 0):
    number_of_zeros = get_number_of_zeros(R)
    print 'number of zeros is {}'.format(number_of_zeros)
    R = randint(0, 2, number_of_zeros)

Result:

number of zeros is 25
number of zeros is 11
number of zeros is 7
number of zeros is 4
number of zeros is 1
number of zeros is 1
number of zeros is 1
number of zeros is 0

Comments

0

Hmm, no need for loops and sums. If you have an array of integers, you can count the number of zeros (or any other individual number) like this:

>>> R = [ 0, 1, 5, 0, 0]
>>> print("There are", R.count(0), "zeros")
There are 3 zeros

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.