Skip to content

Instantly share code, notes, and snippets.

@oskar-j
Created July 21, 2015 22:21
Show Gist options
  • Save oskar-j/babf966aa486a6fa23bb to your computer and use it in GitHub Desktop.
Save oskar-j/babf966aa486a6fa23bb to your computer and use it in GitHub Desktop.
Find lowest index of array's slices having lowest average of elements (in Python)
def solution(A):
min_avg_value = (A[0] + A[1])/2.0 # The mininal average
min_avg_pos = 0 # The begin position of the first
# slice with mininal average
for index in xrange(0, len(A)-2):
# Try the next 2-element slice
if (A[index] + A[index+1]) / 2.0 < min_avg_value:
min_avg_value = (A[index] + A[index+1]) / 2.0
min_avg_pos = index
# Try the next 3-element slice
if (A[index] + A[index+1] + A[index+2]) / 3.0 < min_avg_value:
min_avg_value = (A[index] + A[index+1] + A[index+2]) / 3.0
min_avg_pos = index
# Try the last 2-element slice
if (A[-1]+A[-2])/2.0 < min_avg_value:
min_avg_value = (A[-1]+A[-2])/2.0
min_avg_pos = len(A)-2
return min_avg_pos
@oskar-j
Copy link
Author

oskar-j commented Jul 21, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment