Draw a flowchart and construct a python program to accept a list of N numbers. The job is to determine if there exists an element in the list such that the sum of the elements on its left is equal to the sum of the elements on its right. If such element exists, then print the index of the element. If there are no such elements, then the sum is zero. [CO1] [L2]
Sample workout for better understanding as given below
Input: 6 // length of list
[4, 3, 100, 2, 3, 2] //actual list
Output: 2 (index of the chosen element) (Sum of elements at the left = Sum of elements at the Right = 7)
def solution(fooBar, n) :
preSum = [0] * n
preSum[0] = fooBar[0]
for i in range(1, n) :
preSum[i] = preSum[i - 1] + fooBar[i]
postSum = [0] * n
postSum[n - 1] = fooBar[n - 1]
for i in range(n - 2, -1, -1) :
postSum[i] = postSum[i + 1] + fooBar[i]
for i in range(1, n - 1, 1) :
if preSum[i] == postSum[i] :
return fooBar[i]
return -1
Comments
Leave a comment