代码之家  ›  专栏  ›  技术社区  ›  mike10101

如何按范围10计算阵列的平均值?[已关闭]

  •  -1
  • mike10101  · 技术社区  · 11 年前

    我试图在排序数组中按范围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 回复  |  直到 11 年前
        1
  •  4
  •   Hugh Bothwell    11 年前
    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]