Given a list l of n integers. The task is to find the sum of the product of each element with each element after it in the list. In other words, we have to find the sum of the product of each l[i] with each l[j] such that j > i.
Let’s see an example for better understanding of the problem statement:
Input : l = [9, 3, 4, 2] Output : 107 Sum of product of l[0] with l[1], l[2], l[3] is : 9*3 + 9*4 + 9*2 = 81 Sum of product of l[1] with l[2], l[3] is : 3*4 + 3*2 = 18 Product of arr[2] with arr[3] is : 4*2 = 8 Sum of all these sums is 81 + 18 + 8 = 107 Input : l = [3,5] Output : 15
Below is the implementation:
# Python program to find Sum of product of # each element with each element after it # Define findSOP() function def findSOP(l): result = 0 # outer loop for i in range(len(l) - 1): num = l[i] # assign multiple values # in one line sum , multi = 0, 1 # inner loop # Sum of product of ith element with each element after it for j in range(i+1,len(l)): multi = num * l[j] # sum = sum + multi sum += multi # result = result + sum result += sum # show the result print(result) # main code if __name__ == "__main__": # given input l = [2,3,6,8] # findSOP function call findSOP(l)
Output:
124