In: Computer Science
Write a python function average_sample_median(n,P), that return the average of 1000 samples of size n sampled from the distribution P.
* Sample run :
print(average_sample_median(10,[0.2,0.1,0.15,0.15,0.2,0.2]))
print(average_sample_median(10,[0.3,0.4,0.3]))
print(average_sample_median(10,P=[0.99,0.01])
* Expected Output :
3.7855
2.004
1
Here Iam providing the answer.Hope this helps you.If you have any doubts comment me i will clarify you.Please Upvote if you like my work.Hope you will like this.Thank you :- )
We do this problem in 2 ways.Iam providing 2 ways use what you want :- )
1st Way Using Numpy module:
import numpy as np
def average_sample_median(n, P):
return np.median( np.random.choice ( np.arange (1, len(P) + 1 ), n, p = P ))
print(average_sample_median(10,[0.2,0.1,0.15,0.15,0.2,0.2]))
print(average_sample_median(10,[0.3,0.4,0.3]))
print(average_sample_median(10,[0.99,0.01]))
2nd Way using random module:-
import random
def average_sample_median(n,P):
times = 1000
median_sum = 0
for i in range(times):
samples = random.choices(P, k=n)
sum_p = 0
for j, p in enumerate(samples):
sum_p += p
if sum_p == 0.5:
median_sum += j + 1.5
break
if sum_p > 0.5:
median_sum += j + 1
break
avg_median = median_sum / times
return avg_median
print(average_sample_median(10,[0.2,0.1,0.15,0.15,0.2,0.2]))
print(average_sample_median(10,[0.3,0.4,0.3]))
print(average_sample_median(10,[0.99,0.01]))
Output:-