Program to count average of all special values for all permutations of a list of items in Python

Suppose we have a list of elements we can calculate the value of S by the following algorithm.

while size of L > 1 is non-zero, do
   a := L[0]
   b := L[1]
   remove L[1]
   L[0] := a + b + a*b
return L[0] mod (10^9 + 7)

Here we shall have to find the average of all S values that are calculated from all possible combinations of L.

So, if the input is like L = [5,3,4], then the output will be 199, because for all permutation of L, the value of S is 119, so their average is also 119.

To solve this, we will follow these steps −

  • m := 10^9+7
  • li := a list of x+1 for all x in L
  • prod := 1
  • for each i in li, do
    • prod := prod * i
    • prod := prod mod m
  • return (prod-1) mod m


Let us see the following implementation to get better understanding −

def solve(L):
    m = 10**9+7
    li = [x+1 for x in L]
    prod = 1
    for i in li:
        prod *= i
        prod %= m
    return (prod-1) % m

L = [5,3,4]