[codility]MinAvgTwoSlice

Python代码如下:

def solution(A):
    # write your code in Python 2.6
    # if one slice is the MA, then the average of its subslices
    # can not be smaller and also it can not be bigger, or the average of the 
    # whole slice will change
    # every slice can be divide into two kinds of subslices, e.g., two-element and three element
    
    globalMinAve = sys.float_info.max
    minIndex = 0
    # try two elements
    for i in xrange(0, len(A)-1):
        localAve = (A[i]+A[i+1])/2.0
        if globalMinAve > localAve:
            globalMinAve = localAve
            minIndex = i
    # try three elements
    for i in xrange(0, len(A)-2):
        localAve = (A[i]+A[i+1]+A[i+2])/3.0
        if globalMinAve > localAve:
            globalMinAve = localAve
            minIndex = i
    return minIndex
    pass

你可能感兴趣的:([codility]MinAvgTwoSlice)