简体   繁体   English

不包括最大和最小数的数组总和

[英]Sum of array excluding the maximum and the minimum number

I have to add up excluding the minimum and maximum of any list of numbers.我必须加起来不包括任何数字列表的最小值和最大值。 This code work but it possible using a better solution only with 2 if and do not using a min/max function or another sum function pre existent?这段代码可以工作,但是如果并且不使用最小/最大函数或另一个预先存在的求和函数,则可以仅使用 2 的更好的解决方案?

def total(array):
    sum = 0
    min = array[0]
    max = array[0]
    for x in array:
        if x>max:
            if max != min:
                sum += max
            max = x
    elif x == max:
        pass
    elif x < min:
        if min != max:
            sum += min
        min = x
    elif x == min:
        pass
    else:
         sum+=x
print(min)
print(max)
return sum

This solution utilizes more off-the-shelf functions as opposed to fewer.该解决方案利用了更多的现成功能而不是更少。 That said, it only uses the traditional scientific computing stack so it's something you might want to become familiar with at some point depending on your goals.也就是说,它只使用传统的科学计算堆栈,因此根据您的目标,您可能希望在某个时候熟悉它。 Most importantly, it makes the solution much more readable.最重要的是,它使解决方案更具可读性。

import numpy as np
import pandas as pd

xs = pd.Series([1,2,3,4,5,6,7,8,12])
xs[xs.between(np.min(xs),np.max(xs), inclusive=False)].sum()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM