Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. P
is an index of an array A
.
Input:
A[0] = -1
A[1] = 3
A[2] = -4
A[3] = 5
A[4] = 1
A[5] = -6
A[6] = 2
A[7] = 1
Output:
1
3
7
1 is an equilibrium index of this array, because:
A[0] = −1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7]
3 is an equilibrium index of this array, because:
A[0] + A[1] + A[2] = −2 = A[4] + A[5] + A[6] + A[7]
7 is also an equilibrium index, because:
A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0
My solution for review:
def isEquilibrium(alist, ind):
listLen = len(alist)
left = getSum(0, ind, alist)
right = getSum(ind+1, listLen, alist)
# print left, right
if left == right:
return True
def getSum(start, end, lis):
tot = 0
for i in xrange(start, end):
tot = tot + lis[i]
return tot
def solution(alist):
for i in xrange(0, len(alist)):
result = isEquilibrium(alist, i)
if(result):
print i
solution([-1,3,-4,5,1,-6,2,1])