Dave - 6 months ago 14

Python Question

What logic should be used to update a variable such as a current mean in real time?

For example in the script below

`obs_mean()`

`listen_to_observations()`

How can the value

`current_mean`

`obs_mean(5)`

`import numpy as np`

import random

import time

current_mean = None

def listen_to_observations():

#listen to a stream of observations

time.sleep(1)

yield random.random()

def obs_mean(seconds):

array = [listen_to_observations().next() for i in range(seconds)]

return np.array(array).mean()

How would the logic look like? I am using Python 3.5.

Answer

You could just break up your array line into separate statements, and compute the mean after every observation:

```
import numpy as np
import random
import time
current_mean = None
def listen_to_observations():
#listen to a stream of observations
time.sleep(1)
yield random.random()
def obs_mean(seconds):
array = []
for i in range(seconds):
array.append(listen_to_observations().next())
current_mean = np.array(array).mean()
print('current_mean = {}'.format(current_mean))
return current_mean
if __name__ == '__main__':
obs_mean(5)
```

*My output:*

```
current_mean = 0.193142347659
current_mean = 0.212120380098
current_mean = 0.355774933848
current_mean = 0.362840457341
current_mean = 0.312662693142
```