[Tutor] increment a counter inside generator
Oscar Benjamin
oscar.j.benjamin at gmail.com
Wed Mar 13 22:02:23 CET 2013
On 13 March 2013 19:50, Abhishek Pratap <abhishek.vit at gmail.com> wrote:
> Hey Guys
>
> I might be missing something obvious here.
>
>
> import numpy as np
>
> count = 0
> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20]
>
> File "<ipython-input-45-0ba0e51b7644>", line 2
> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20]
> ^
> SyntaxError: invalid syntax
I think this does what you want:
>>> import numpy as np
>>> a = np.random.random_integers(1, 100, 20)
>>> (a > 20).sum()
17
I don't know if this really applies to what you're doing but the
result of this computation is a binomially distributed random number
that you could generate directly (without creating the intermediate
array):
>>> np.random.binomial(100, .2)
26
Oscar
More information about the Tutor
mailing list