Python is a high-level programming language that provides a range of modules and functions. The heap
structure is used to represent priority queues and comes with the heapq
module. There is a multitude of methods that can be performed on these structures. The nsmallest()
and nlargest()
methods can be used to find the smallest and largest values in a heap, respectively.
nsmallest(k, iterable, key = fun)
nlargest(k, iterable, key = fun)
k
: Specifies the number of smallest/largest elements to be returned. This parameter is required.iterable
: Specifies the iterable to extract the smallest/largest values from. This parameter is required.key
(Optional): Specifies a function that has only one argument. If specified, a comparison key is extracted from each item in the iterable.The nsmallest()
method returns k
smallest values, while the nlargest()
method returns k
largest values in the iterable.
#import libraryimport heapq#initialize listslist1=[5, 12, 93, 1, 53, 17, 9]list2=[4.8, 9.2, 12.6, 47.3, 16.5]#print listsprint('List 1:',list1)print('List 2:',list2)#print smallest valuesprint('3 smallest values of list 1:', heapq.nsmallest(3,list1))print('2 smallest values of list 2:', heapq.nsmallest(2,list2))#print largest valuesprint('3 largest values of list 1:', heapq.nlargest(3,list1))print('2 largest values of list 2:', heapq.nlargest(2,list2))