[Solved] calculate and return the difference between the second largest number and the second smallest number [closed]


Here is a simple, but not most efficient way. you can achieve that by two step:

  1. convert list to set, to remove the duplicate number.
  2. use heap to find nlargest and nsmallest in set
def difference(list1):
    set1 = set(list1)
    return heapq.nlargest(2, set1)[1] - heapq.nsmallest(2, set1)[1]

Here is a one pass way, more efficient way, use 4 variables:

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

test and output:

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

Hope that helps you, and comment if you have further questions. : )

solved calculate and return the difference between the second largest number and the second smallest number [closed]