• API
• FAQ
• Tools
• Archive
SHARE
TWEET

Untitled

a guest Jan 27th, 2020 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1.
2. def expect(xDistribution, function):
3.
4. ##################################################
6. ##################################################
7.     total = 0
8.
9.     for n in xDistribution.keys():
10.         total += xDistribution[n] * function(n)
11.
13.     # return sum([xDistribution[val] * function(val) for val in xDistribution.keys()])
14.
15.
16.
17. ##################################################
18. #       Your code below each comment
19. ##################################################
20. def getVariance(xDistribution):
21.
22.     #Step 1 - Calculate the expected value E(X)
23.     expected_val = expect(xDistribution, lambda x: x)
24.
25.     def getSquaredDistanceToMu(x):
26.     #Step 2 - Calculate (X-E(X))^2
27.         return (x - expected_val) ** 2
28.     #Step 3 - Calculate Variance: Var(X)=E((X-E(X))^2)
29.     variance = expect(xDistribution, getSquaredDistanceToMu)
30.
31.     return variance
32.
33. def main():
34.     xDistributionExample1={1: 1/5, 2: 2/5, 3: 2/5}
35.     functionExample1=lambda x: x ** 2
36.     print("Expected value:", expect(xDistributionExample1, functionExample1))
37.     print("Variance:", getVariance(xDistributionExample1))
38.
39.     xDistributionExample2={1: 1/6, -1/2: 1/3, 1/3: 1/4, -1/4: 1/12, 1/5: 1/6}
40.     functionExample2=lambda x: 1/x
41.     print("Expected value:", expect(xDistributionExample2, functionExample2))
42.     print("Variance:", getVariance(xDistributionExample2))
43.
44.
45. if __name__ == '__main__':
46.     main()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.
Top