Home > Software engineering >  Sum of Multiplication of each number with sum of other numbers of an array in rotational manner
Sum of Multiplication of each number with sum of other numbers of an array in rotational manner

Time:11-14

Example:

Input : [4 3 5 1]
Output: 118

Explanation:

4*(3 5 1)=>36
3*(4 5 1)=>30
5*(4 3 1)=>40
1*(4 3 1)=>12
Therefore, (36 30 40 12=)118

What would be the code to implement it?

CodePudding user response:

You can use sum with generator comprehension:

lst = [4, 3, 5, 1]

output = sum(x * (sum(lst) - x) for x in lst)
print(output) # 118

If there the list is long, then you might want to pre-calculate sum(lst) and store it in a separate variable.

CodePudding user response:

You can obtain that result by subtracting the sum of squares from the square of the sum:

a = [4,3,5,1]

sum(a)**2 - sum(n**2 for n in a)  # 118
  • Related