Skip to content

Instantly share code, notes, and snippets.

@jaylett
Forked from tomwolber/equi2.py
Last active December 12, 2015 09:39
Show Gist options
  • Save jaylett/4753500 to your computer and use it in GitHub Desktop.
Save jaylett/4753500 to your computer and use it in GitHub Desktop.
tests = [
([-7, 1, 5, 2, -4, 3, 0], [3,6]),
([1, 2, 3, 4, 3, 2, 1], [3]),
([99, 0, 66, 32, 1] , [1]),
([1, -1, 1, -1, 1, -1, 1], [0,1,2,3,4,5,6]),
([0,0,0], [0,1,2]),
([0,53,9], -1),
([0,1,-1], [0]),
([-1, 0, 1], -1),
]
def equi(A):
s = [] # list of eq. indices
for i in range(len(A)):
if sum(A[:i]) == sum(A[i+1:]):
s.append(i)
if s:
return s
else:
return -1
def fast_equi(A):
l = 0 # left of current index
r = sum(A) # right of current index
s = [] # list of eq. indices
for i in range(len(A)):
r -= A[i]
if l == r:
s.append(i)
l += A[i]
if s:
return s
else:
return -1
if __name__ == "__main__":
for (i, r) in tests:
if r != equi(i):
print r, "!=", equi(i), "for", i
if r != fast_equi(i):
print r, "!=", fast_equi(i), "for", i, "(fast)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment