Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def expect(xDistribution, function):
- ##################################################
- # Your code here
- ##################################################
- total = 0
- for n in xDistribution.keys():
- total += xDistribution[n] * function(n)
- return total
- # return sum([xDistribution[val] * function(val) for val in xDistribution.keys()])
- ##################################################
- # Your code below each comment
- ##################################################
- def getVariance(xDistribution):
- #Step 1 - Calculate the expected value E(X)
- expected_val = expect(xDistribution, lambda x: x)
- def getSquaredDistanceToMu(x):
- #Step 2 - Calculate (X-E(X))^2
- return (x - expected_val) ** 2
- #Step 3 - Calculate Variance: Var(X)=E((X-E(X))^2)
- variance = expect(xDistribution, getSquaredDistanceToMu)
- return variance
- def main():
- xDistributionExample1={1: 1/5, 2: 2/5, 3: 2/5}
- functionExample1=lambda x: x ** 2
- print("Expected value:", expect(xDistributionExample1, functionExample1))
- print("Variance:", getVariance(xDistributionExample1))
- xDistributionExample2={1: 1/6, -1/2: 1/3, 1/3: 1/4, -1/4: 1/12, 1/5: 1/6}
- functionExample2=lambda x: 1/x
- print("Expected value:", expect(xDistributionExample2, functionExample2))
- print("Variance:", getVariance(xDistributionExample2))
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement