[Tutor] increment a counter inside generator

Abhishek Pratap abhishek.vit at gmail.com
Wed Mar 13 22:12:22 CET 2013


On Wed, Mar 13, 2013 at 2:02 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> 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

Hi Oscar

I just used a very contrived example to ask if we can increment a
counter inside a generator. The real case is more specific and
dependent on other code and not necessarily useful for the question.

-Abhi


More information about the Tutor mailing list