简体   繁体   中英

Independent random variables: PMF calculation

Consider random variables 𝑋 and 𝑌 . Assume that 𝑋 takes values 𝑥1,…,𝑥𝑛 with probabilities 𝑝1,…,𝑝𝑛 and 𝑌 takes values 𝑦1,…,𝑦𝑚 with probabilities 𝑞1,…,𝑞𝑚 . Assume that 𝑋 and 𝑌 are independent. Implement function joint_pmf(xvalues, xprobs, yvalues, yprobs) that takes an array of values 𝑥1,…,𝑥𝑛 as xvalues, an array of probabilities 𝑝1,…,𝑝𝑛 as xprobs and the same with yvalues and yprobs. The function should return a dictionary which keys are tuples (x, y) where x is some value 𝑥𝑖 and y is 𝑦𝑗 and corresponding values are values of joint probability mass function 𝑝𝑚𝑓𝑋,𝑌(𝑥𝑖,𝑦𝑗)

def joint_pmf(xvalues, xprobs, yvalues, yprobs):
     # your code

testdata = [([1], [1], [2, 3], [0.2, 0.8]),
            ([1, 2], [0.5, 0.5], [3, 4, 5], [0.3, 0.3, 0.4])]
answers = [{(1, 2): 0.2, (1, 3): 0.8},
           {(1, 3): 0.15,
            (1, 4): 0.15,
            (1, 5): 0.2,
            (2, 3): 0.15,
            (2, 4): 0.15,
            (2, 5): 0.2}]

for data, answer in zip(testdata, answers):
    assert joint_pmf(*data) == answer

I can't understand the task before going to the solution. For example, there are only two probabilities in testdata for 4 x values ([1], [1], [2, 3], [0.2, 0.8])? Why is there no such value in answers like x=1 and y=1? {(1,1): ...}? Could you please give an explanation or your solution?

def joint_pmf(xvalues, xprobs, yvalues, yprobs):
    jpm = {}
    for i in range(len(xvalues)):
        for j in range(len(yvalues)):
            jpm[(xvalues[i],yvalues[j])] = xprobs[i]*yprobs[j]
    return jpm

may be more elegant solution?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM