最重和最轻

伪代码表达上述逻辑关系

ages = [n1,n2,n3,n4,n5]

ages = sorted(ages) #ascending order

lightest4_average = sum(ages[:-1])/4 = 40 #切片slice

heavest4_average = sum(ages[1:])/4 = 45

so that :

sum(ages[:-1]) = 160 .AND. sum(ages[1:]) = 180

max(ages) - min(ages) = 180 - 160 = 20

1- what is possible range of sum(ages)?

we could suppose that ages = [n1,n2,n3,n4,n1+20]

Since that n1<= n2<= n3<<=n4<=n1+20, if 5 numbers satisfied with above condition,meanwhile 5 numbers is as small as possible, or as big as possible

we find that : sum(ages) / 5 =>

40*4/5 + (n1+20)/5 = 32 + 4 + n1/5 = 36 + n1/5

45*4/5 + n1/5 = 36 + n1/5

2- What is the range of n1 ?

Since 25 <=n1 <= 40, 36+25/5 = 41; 36+40/5 = 44

Answer is D = 3kg

如何运用编程解决之?

def averageRange(n,lavrg,havrg):
    '''
    :param n: 共有n个人
    :param lavrg: n-1个最轻的平均体重
    :param havrg: n-1个最重的平均体重
    :return: 所有n人人的平均体重的上下范围

    # 1...n从轻到重排序,第1人的重量最轻为 w1
    # Wn - W1即最重 - 最轻为确定的 gap = (havrg- lavrg)*(n-1)
    # 当第2,3..n人重量相同时,第1人最轻,思考why?
      w1 + (w1+gap)*(n-2) = lavrg*(n-1)
    # 当第1,2..n-1人重量相同时,第1人最重,思考why?
      w1*(n-2) + (w1+gap) = havrg*(n-1)
    # average_range = havrg * (n-1)/n + w1
    (Maxw1 + havrg * (n-1))/n, (MinW1+havrg * (n-1))/n

    '''
    gap = (havrg - lavrg)*(n-1)
    MinW1 = (lavrg*(n-1) - gap*(n-2))/(n-1)
    Maxw1 = (havrg*(n-1) - gap)/(n-1)
    return (Maxw1 + havrg * (n-1))/n, (MinW1+havrg * (n-1))/n

n,lavrg,havrg = 5,40,45
print(averageRange(n,lavrg,havrg))

本文由mdnice多平台发布

你可能感兴趣的:(最重和最轻)