# Program to find expected value of maximum occurred frequency values of expression results in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have M different expressions, and the answers of these expressions are in range 1 to N (both inclusive) So consider x = max(f(i)) for each i in range 1 through N, we have to find the expected value of x.

So, if the input is like M = 3, N = 3, then the output will be 2.2, because

SequenceMaximum frequency
1113
1122
1132
1222
1231
1331
2223
2232
2332
3333

$$E(x) = \sum P(x) * x = P(1) + 2P(2) + 3P(3) = \frac{1}{10} + 2 * \frac{6}{10} + 3 * \frac{3}{10} = \frac{22}{10}$$

To solve this, we will follow these steps −

• combination := a new map
• Define a function nCr() . This will take n, k_in
• k := minimum of k_in and (n - k_in)
• if n < k or k < 0, then
• return 0
• otherwise when (n, k) is in combination, then
• return combination[n, k]
• otherwise when k is same as 0, then
• return 1
• otherwise when n is same as k, then
• return 1
• otherwise,
• a := 1
• for cnt in range 0 to k - 1, do
• a := a * (n - cnt)
• a := floor of a/(cnt + 1)
• combination[n, cnt + 1] := a
• return a
• From the main method, do the following:
• arr := a new list
• for k in range 2 to M + 1, do
• a := 1
• s := 0
• for i in range 0 to floor of M/k + 2, do
• if M < i * k, then
• come out from loop
• s := s + a * nCr(N, i) * nCr(N-1+M-i*k, M-i*k)
• a := -a
• insert s at the end of arr
• total := last element of arr
• diff := an array where insert arr[0] at beginning then add a list where (arr[cnt + 1] - arr[cnt]) for each cnt in range 0 to M - 2
• output := sum of all elements present in (diff[cnt] *(cnt + 1) / total for cnt in range 0 to M-1)
• return output

## Example

Let us see the following implementation to get better understanding −

combination = {}
def nCr(n, k_in):
k = min(k_in, n - k_in)
if n < k or k < 0:
return 0
elif (n, k) in combination:
return combination[(n, k)]
elif k == 0:
return 1
elif n == k:
return 1
else:
a = 1
for cnt in range(k):
a *= (n - cnt)
a //= (cnt + 1)
combination[(n, cnt + 1)] = a
return a

def solve(M, N):
arr = []
for k in range(2, M + 2):
a = 1
s = 0
for i in range(M // k + 2):
if (M < i * k):
break
s += a * nCr(N, i) * nCr(N - 1 + M - i * k, M - i * k)
a *= -1
arr.append(s)
total = arr[-1]
diff = [arr[0]] + [arr[cnt + 1] - arr[cnt] for cnt in range(M - 1)]
output = sum(diff[cnt] * (cnt + 1) / total for cnt in range(M))
return output

M = 3
N = 3
print(solve(M, N))

## Input

3, 3

## Output

1
Updated on 11-Oct-2021 09:20:44