0

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?

evggenn
  • 23
  • 4
  • 1
    "Why is there no such value in answers like x=1 and y=1? {(1,1): ...}?" - because there is no `y=`. There are two tuples in `testdata`, each one contains four arguments (xval, xprob, yval, yprob). So for example in first tuple `yval=[2,3]` and `yprob=[0.2,0.8]`. And in the first tuple you can form two pairs from `xval` and `yval`: `(1,2)` and `(1,3)`. – Rafaó May 23 '22 at 10:38
  • @Rafaó How to understand second testdata tuple ([1, 2], [0.5, 0.5], [3, 4, 5], [0.3, 0.3, 0.4])? x=1 y=2? for which values x and y are two probabilities 0.5 and 0.5? – evggenn May 23 '22 at 10:57
  • 1
    xval=[1,2], xprob=[0.5,0.5], yval=[3, 4, 5], yprob=[0.3, 0.3, 0.4]. So, for example, prob for x=1 is 0.5, prob for y=4 is 0.3, prob for y=5 is 0.4. – Rafaó May 23 '22 at 11:03
  • I think I got it). If variables are independent their joint probability is their product. In the first tuple there is only one value of x=1 with probability 1. That's why P(1,2)=1 x 0.2 = 0.2 – evggenn May 23 '22 at 11:39

1 Answers1

0
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?

evggenn
  • 23
  • 4