# Python Program to calculate function from indicator random variable from given condition

PythonServer Side ProgrammingProgramming

Suppose we have two values k and n. Consider a random permutation say p1, p2, ..., pn of first n natural numbers numbers 1, 2, ..., n and calculate the value F, such that F = (X2+...+Xn-1)k, where Xi is an indicator random variable, which is 1 when one of the following two conditions holds: pi-1 < pi > pi+1 or pi-1 > pi < pi+1 and Xi is 0 otherwise. We have to find the expected value of F.

So, if the input is like k = 1 n = 1000, then the output will be 1996/3

To solve this, we will follow these steps −

• Define a function exp_factor() . This will take n,k
• if k is same as 1, then
• return(2*(n-2) , 3)
• otherwise when k is same as 2, then
• return (40*n^2 -144*n + 131, 90)
• otherwise when k is same as 3, then
• return (280*n^3 - 1344*n^2 +2063*n -1038,945)
• otherwise when k is same as 4, then
• return (2800*n^4 - 15680*n^3 + 28844*n^2 - 19288*n + 4263, 14175)
• otherwise when k is same as 5, then
• return (12320*n^5 - 73920*n^4 + 130328*n^3 - 29568*n^2 - 64150*n -5124, 93555)
• return 1.0
• From the main method, do the following −
• M := n-2
• p := 2.0/3
• q := 1 - p
• (num, den) := exp_factor(n, k)
• g := gcd(num, den)
• return fraction (num/g) / (den/g)

## Example

Let us see the following implementation to get better understanding −

from math import gcd

def exp_factor(n,k):
if k == 1:
return (2*(n-2),3)
elif k == 2:
return (40*n**2 -144*n + 131,90)
elif k == 3:
return (280*n**3 - 1344*n**2 +2063*n -1038,945)
elif k == 4:
return (2800*n**4 - 15680*n**3 + 28844*n**2 - 19288*n + 4263, 14175)
elif k == 5:
return (12320*n**5 - 73920*n**4 + 130328*n**3 - 29568*n**2 - 64150*n -5124, 93555)
return 1.0

def solve(k, n):
M = n-2
p = 2.0/3
q = 1 - p

num, den = exp_factor(n,k)
g = gcd(num, den)
return str(int(num/g))+'/'+str(int(den/g))

k = 1
n = 1000
print(solve(k, n))

## Input

1, 1000

## Output

1996/3