def equi(A): totals = list() accum = 0 for element in A: totals.append(accum) accum += element for idx in range(0, len(A)): if totals[idx] == accum - totals[idx] - A[idx]: return idx return -1
Definition of Equilibrium index:
Quote:
Equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in a sequence A:
A[0]=-7 A[1]=1 A[2]=5 A[3]=2 A[4]=-4 A[5]=3 A[6]=0
3 is an equilibrium index, because : :
A[0] A[1] A[2] = A[4] A[5] A[6]
6 is also an equilibrium index, because:
A[0] A[1] A[2] A[3] A[4] + A[5] = 0 (sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence A.
If you still have doubts, this is a precise definition: the integer k is an equilibrium index of a sequence
A[0],A[1],...,A[n] if and only if 0≤k≤ n and Σm=0 k−1 A[m]=Σm=k+1 n A[m]. We assume that sum of zero elements is equal zero.
Write a function, that given a sequence, returns its equilibrium index (any) or -1 if no equilibrium indexes exist. Assume that the sequence may be very long. If possible, use one of the following languages and define your function as follows: int equi(int a[])
Originating thread: Equilibrium problem
[Edited by - Alpha_ProgDes on September 18, 2010 8:01:04 PM]