【问题标题】:calculate and return the difference between the second largest number and the second smallest number [closed]计算并返回第二大数字和第二小数字之间的差[关闭]
【发布时间】:2019-04-08 09:20:03
【问题描述】:

给定一个 Python 列表,计算并返回第二大数和第二小数之间的差。假设列表包含两个或更多元素。 功能规格: 第二大/最小的数字必须不同于列表中的最大/最小数字。那就是:

difference([10, 10, 10, 8, 5, 2, 1, 1, 1]) == 8 - 2 == 6

应该将列表作为输入。

def difference(list1):

    # Your code here

    return* 

【问题讨论】:

  • 你已经尝试了什么?
  • 你有什么问题?
  • 我试过这个:# def difference(list1): return list1[::-1] difference = difference([10, 10, 10, 8, 5, 2, 1, 1, 1 ]) print(difference) # 它似乎能够对列表进行排序,但我不能让它减去最大的数字和第二大的数字,因为我需要排序并返回最后两个数字之间的差。

标签: python sorting nested-lists numpy-slicing


【解决方案1】:

首先,我们从给定列表中构造一个集合以删除重复值,然后对它们进行排序以轻松找到第二高和第二小的值。

def difference(list1):
    list1 = sorted(set(list1))
    print(list1) # --> [1, 2, 5, 8, 10]

    if list1[1] != list1[-2]:
        return list1[-2] - list1[1]

print(difference([10, 10, 10, 8, 5, 2, 1, 1, 1]) == 8 - 2 == 6) # --> True

【讨论】:

    【解决方案2】:

    这是一个简单但不是最有效的方法。您可以通过两步来实现:

    1. list 转换为set,以删除重复号码。
    2. 使用heapset 中查找nlargestnsmallest
    def difference(list1):
        set1 = set(list1)
        return heapq.nlargest(2, set1)[1] - heapq.nsmallest(2, set1)[1]
    

    这里是一种单程,更高效的方式,使用 4 个变量:

    def difference(list1):
        max1, max2, min1, min2 = float('-inf'), float('-inf'), float('inf'), float('inf')
        for x in list1:
            if x > max1:
                max1, max2 = x, max1
            elif x >= max2 and x != max1:
                max2 = x
    
            if x < min1:
                min1, min2 = x, min1
            elif x <= min2 and x != min1:
                min2 = x
    
        return max2 - min2
    

    测试和输出:

    print(difference([10, 10, 10, 8, 5, 2, 1, 1, 1]))
    # 6
    

    希望对您有所帮助,如果您有其他问题,请发表评论。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2014-02-12
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      相关资源
      最近更新 更多