Skip to content

Instantly share code, notes, and snippets.

@darkf
Last active December 16, 2015 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkf/5499447 to your computer and use it in GitHub Desktop.
Save darkf/5499447 to your computer and use it in GitHub Desktop.
Find the indices where the sum on both sides of the medians is equal, or something
import math
def sumPoint(nums, n):
acc = 0
for i,x in enumerate(nums):
acc += x
if acc == n:
return i
return None
def findMidSum(nums):
n = len(nums)
midpoint_index = int(math.ceil(n/2.)) - 1
midpoint_sum = sum(nums[:midpoint_index+1])
left_index = sumPoint(nums, midpoint_sum)
right_index = sumPoint(reversed(nums), midpoint_sum)
if left_index != midpoint_index and right_index != midpoint_index:
return None # no match
return (left_index+1, right_index+1)
if __name__ == "__main__":
numbers = [4, 5, 6, 7, 8]
#numbers = [1, 3, 1, 2, 3]
#numbers = [5, 5, 8, 2]
print findMidSum(numbers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment