Program to find sum of the 2 power sum of all subarray sums of a given array in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list A. We have taken all non-empty sublists of A as we know a list l with n elements has (2n - 1) non-empty sublist. Now for each sublist, he calculates sublist_sum (the sum of elements and denotes them by S1, S2, S3, ... , S(2N-1)). There is a special sum P such that P = 2S1 + 2S2 +2S3 .... + 2S(2N-1). We have to find P. If P is too large then return P mod (10^9 + 7).

So, if the input is like A = [2,2,3], then the output will be The subsets are

  • {2} so 2^2 = 4
  • {2} so 2^2 = 4
  • {3} so 2^3 = 8
  • {2,2} so 2^4 = 16
  • {2,3} so 2^5 = 32
  • {2,3} so 2^5 = 32
  • {2,2,3} so 2^7 = 128

Sum is 4 + 4 + 8 + 16 + 32 + 32 + 128 = 224

To solve this, we will follow these steps −

  • ans:= 1
  • m:= 10^9+7
  • for each el in A, do
    • ans := ans *(1 + (2^el mod m))
    • ans := ans mod m
  • return (m + ans-1) mod m

Example

Let us see the following implementation to get better understanding −

def solve(A):
   ans=1
   m=10**9+7

   for el in A:
      ans *= (1+pow(2,el,m))
      ans %= m
   return (m+ans-1) % m


A = [2,2,3]
print(solve(A))

Input

[2,2,3]

Output

224
raja
Updated on 25-Oct-2021 07:05:24

Advertisements