How to Construct an array from its pair-sum array in Python

In this tutorial we are going to learn how to construct an array from its pair-sum array in Python. It is an array that consists of the sum of all the pairs in an orderly fashion. So, in general pair-sum array for array[0..n-1] is : –
{array[0]+array[1], array[0]+array[2], ……, array[0]+array[n-1],array[1]+array[2], array[1]+array[3], ……., array[2]+array[3], array[2]+array[4], …., array[n-2]+array[n-1]}.

Construct an Array from its pair-sum array in Python

If we are given an array called sum and there are n elements in the array that we are constructing that is named array. And by seeing some examples we can observe that we can calculate the first element of the original array by: –

Dividing the sum[0]+sum[1]-sum[n-1] by 2 that is generally (array[0]+array[1])+(array[2]+array[0])-(array[1]-array[2]). We see that array[1] and array[2] will be canceled out and 2*array[0] will remain that is divided by 2 to get the first element. So, now as we know the value of array[0] we can get the value of array[1] by subtracting array[0] from sum[0]=(array[0]+array[1]). Similarly, we can get all the values by subtracting array[0] from subsequent sum elements.

Now we are going to implement it in Python: –

Code: –

Firstly we are going to create a function based on the above algorithm.

def mainarray(array,sum,n):
    array[0] = (sum[0]+sum[1]-sum[n-1])//2
    for i in range(1,n): 
        array[i] = sum[i-1]-array[0]

Now we are going to initialize the sum array and the array of original numbers.

Code: –

sum=[14, 9, 10, 11, 12, 7]
array=[0]*n #We initialize an array of size n with 0
for i in range(n):
    print(array[i],end=" ")

We are calling the mainarray function by giving the required parameters.

Output: –

6 8 3 4

We see that we are getting the correct output after calling the function. Similarly, this algorithm can be applied to any language.

Also Read: –

How to find all possible pairs with given sum in Python lists

Leave a Reply

Your email address will not be published. Required fields are marked *