Created
October 12, 2012 23:22
-
-
Save LuchoLopez/3882223 to your computer and use it in GitHub Desktop.
A little function that recives a list, return equilibrium index (-1 when no equilibrium index is found) or index+1 (only when the sum of all list components is equal to zero) and returns another list with solutions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A is a list object | |
def equi ( A ): | |
# solution will store all solutions to the problem | |
solution = list() | |
# the sum of all list components | |
A_sum = 0 | |
# iterates for each element in the list | |
for index in range( len( A ) ): | |
A_sum += A[index] | |
# stores the sum of all components at left of this index position | |
sumaizq = 0 | |
# stores the sum of all components at right of this index position | |
sumader = 0 | |
for i in range( index ): | |
sumaizq += A[i] | |
for i in range( index + 1, len( A ) ): | |
sumader += A[i] | |
if sumader == sumaizq: | |
solution.append( index ) | |
# if no equilibrium point was found, then add -1 to solution. | |
if len(solution) == 0: | |
solution.append( -1 ) | |
# if the sum of all elements of the list is equal to 0, then add the length-1 of the list | |
if A_sum == 0: | |
solution.append( len( A ) - 1 ) | |
return solution |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment