Python is undoubtedly one of the most widely used programming languages of this century that has given a whole new perspective to programming in terms of ease of use and intuitiveness. Besides having a rich set of the most common data structures, it provides a number of standard libraries that can greatly reduce the burden of developing codes from scratch for a variety of problems pertaining to different fields. In this tutorial, I will focus on some of the most common problems or should I say, encounters, and their solutions using data structures and algorithms of standard python modules. So let’s dive into the world of “Python+” which is all about adding something more into what we know of Python.
1. N largest or smallest elements in a list, tuple, set or numpy array
In many scenarios, we need to extract the largest or smallest elements in a collection. The nlargest and nsmallest methods of the heapq module of python can be used to obtain N largest and smallest elements in a list. nlargest(n,iterable)
and nsmallest(n,iterable)
where n
is the number of largest or smallest elements that need to be obtained and iterable
can be a list, a tuple, a set or a numpy array can be used as follows.
Figure 1. Smallest and largest elements in a list, tuple and array
These methods are faster and more efficient in case more than one largest or smallest elements in a collection is needed. If the single largest or smallest element is needed, the min
and max
functions in python are more efficient. Note that the _nlargest_
and _nsmallest_
functions always return a list irrespective of the type of the collection.
#python-standard-library #python #data-structures #algorithms #data-science