如何计算10个范围内的数组平均值?

时间:2015-02-10 15:48:31

标签: python arrays algorithm average

我试图在排序数组中按范围10查找数组的平均值,例如:[1,2,3,5,11,12,13,15,22,25,27,30]应该返回[6,17,27]
该函数应该将数字组合在10的范围内并使其之间的平均值 [1,2,3,5,11] =(1 + 11)/ 2 = 6

[12,13,15,22] =(12 + 22)/ 2 = 17

[25,27,30] =(25 + 30)/ 2 = 27

这是我的代码

def par(s):

    g = []
    i = 0
    while i <= len(s):
        y =s[i] + 10

        n = (s[i]+y)/2
        g.append(n)

        for x in s:
            if y <= x:
                i = s.index(x)
                break

    return g 

1 个答案:

答案 0 :(得分:4)

data = [1,2,3,5,11,12,13,15,22,25,27,30]

# divide it into blocks like [[a .. a+10], [b .. b+10], ...]
result = []
block  = None
for d in data:
    if block:
        if d <= hi:
            # belongs to current block
            block.append(d)
        else:
            # start a new block
            result.append(block)  # finish previous block
            block = [d]           # start new block
            lo, hi = d, d + 10    # reset endpoints for new block
    else:
        # special handling for first value encountered
        block = [d]
        lo, hi = d, d + 10
# cleanup
if block:
    result.append(block)

# result = [[1, 2, 3, 5, 11], [12, 13, 15, 22], [25, 27, 30]]

# find midpoint for each block
mid_points = [(block[0] + block[-1]) // 2 for block in result]

# mid_points = [6, 17, 27]