在Python中查找表达式结果的最大出现频率值的期望值的程序
假设我们有M个不同的表达式,并且这些表达式的答案在1到N的范围内(两者都包括在内)所以考虑x=max(f(i))对于范围1到N中的每个i,我们必须找到x的期望值。
所以,如果输入像M=3,N=3,那么输出将是2.2,因为
$$E(x)=\sumP(x)*x=P(1)+2P(2)+3P(3)=\frac{1}{10}+2*\frac{6}{10}+3*\frac{3}{10}=\frac{22}{10}$$
示例
让我们看看以下实现以获得更好的理解-
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))
输入
3, 3输出结果
1