163k views
1 vote
Write a function sample_median(n,P) that generates n random values using distribution P and returns the median of the collected sample. Hint: Use function random.choice() to sample data from P and median() to find the median of the samples * Sample run * print(sample_median(10,[0.1 0.2 0.1 0.3 0.1 0.2])) print(sample_median(10,[0.1 0.2 0.1 0.3 0.1 0.2])) print(sample_median(5,P=[0.3,0.7]) print(sample_median(5,P=[0.3,0.7]) * Expected Output * 4.5 4.0 2.0 1.0

User KexAri
by
5.7k points

1 Answer

0 votes

Answer:

import numpy as np

def sample_median(n, P):

return np.median( np.random.choice ( np.arange (1, len(P) + 1 ), n, p = P ) )

print(sample_median(10,[0.1 0.2 0.1 0.3 0.1 0.2]))

print(sample_median(10,[0.1 0.2 0.1 0.3 0.1 0.2]))

print(sample_median(5, [0.3,0.7])

print(sample_median(5, [0.3,0.7])

Step-by-step explanation:

  • Bring in the numpy library to use the median function provided by the numpy library.
  • Define the sample_median function that takes in 2 parameters and returns the median with the help of built-in random, choice and arrange functions.
  • Call the sample_median function by providing some values to test and then display the results.

Output:

4.5

4.0

2.0

1.0

User Niranjan Borawake
by
6.5k points