Blog

  • Python bin() Function

    The python bin() function is used to return the binary representation of a specified integer. A result always starts with the prefix 0b.

    Python bin() Function Syntax

    It has the following syntax:

    bin(n)

    Parameters

    • n: It represents an integer.

    Return

    It returns the binary representation of a specified integer.

    Python bin() Function Example 1

    Let us take an example to demonstrate the python bin() function.

    x =  10  
    
    y =  bin(x)  
    
    print (y)

    Output:

    0b1010
    

    Note: The result will always be prefixed with ‘0b’.

  • Python all() Function

    The python all() function accepts an iterable object (such as list,dictionary etc.). It returns True if all items in passed iterable are true, otherwise it returns False. If the iterable object is empty, the all() function returns True.

    Python all() Function Syntax

    It has the following syntax:

    all (iterable)  

    Parameters

    • iterable – The objects which contain the elements i.e. list, tuple and dictionary, etc.

    Return

    • True: If all the elements in an iterable are true.
    • False: If all the elements in an iterable are false..

    Python all() Function Example 1

    Let us take an example to demonstrate the all() function in Python.

    # all values true  
    
    k = [1, 3, 4, 5]  
    
    print(all(k))  
    
      
    
    # all values false  
    
    k = [0, False]  
    
    print(all(k))  
    
      
    
    # one false value  
    
    k = [1, 3, 4, 0]  
    
    print(all(k))  
    
      
    
    # one true value  
    
    k = [0, False, 5]  
    
    print(all(k))  
    
      
    
    # empty iterable  
    
    k = []  
    
    print(all(k))

    Output:

    True
    False
    False
    False
    True
    

    Python all() Function Example 2

    The below example shows how all() works for dictionaries.

    # Both the keys are true  
    
    dict1 = {1: 'True', 2: 'False'}  
    
    print(all(dict1))  
    
      
    
    # One of the key is false  
    
    dict2 = {0: 'True', 1: 'True'}  
    
    print(all(dict2))  
    
      
    
    # Both the keys are false  
    
    dict3 = {0: 'True', False: 0}  
    
    print(all(dict3))  
    
      
    
    # Empty dictionary  
    
    dict4 = {}  
    
    print(all(dict4))  
    
      
    
    # Here the key is actually true because  
    
    #  0 is non-null string rather than a zero  
    
    dict5 = {'0': 'True'}  
    
    print(all(dict5))

    Output:

    True
    False
    False
    True
    True
    

    Python all() Function Example 3

    The below example shows how all() works for tuples.

    # all true values  
    
    t1 = (1, 2, 3, 4, 5)  
    
    print(all(t1))  
    
      
    
    # one false value  
    
    t2 = (0, 1, "Hello")  
    
    print(all(t2))  
    
      
    
    # all false values  
    
    t3 = (0, False , 0)  
    
    print(all(t3))  
    
      
    
    # one true value, all false  
    
    t4 = (True, 0, False)  
    
    print(all(t4))

    Output:

    True
    False
    False
    False
  • Python abs() Function

    The Python abs() function is used to return the absolute value of a number. The absolute function returns a positive number if the original number is negative.

    Syntax:

    abs (num)  

    Parameters

    num: A number whose absolute value is to be returned, such as an integer, a floating number, or a complex number.

    Return: It returns the absolute value of the specified number.

    Python abs() Function Examples

    abs() Function with an Integer Argument

    We can use the abs() function to convert a negative integer into a positive integer.

    Example

    Let’s see an example, where we will see, a negative integer getting converted to a positive integer.

    #integer number    
    
    neg_integer = -100    
    
    #finding the absolute value using the abs() function  
    
    print('Absolute value of -100 is:', abs(neg_integer))

    Output:

    Absolute value of -100 is: 100

    abs() Function with a Floating-Point Number

    Similarly, we can convert a negative floating number into a positive floating number by using the abs() function.

    Example

    Let’s see an example, where we will see, a negative floating-point number getting converted to a positive floating-point number.

    # below is a floating-point number  
    
    float_number = -69.96  
    
    #finding the absolute value using the abs() function  
    
    print("Absolute value of float number", float_number, "is: ",abs(float_number))

    Output:

    Absolute value of float number -69.96 is: 69.96

    abs() Function with a Complex Number

    The complex number consists of a real part and an imaginary part. We can pass the complex number through the abs() function, and we will get an absolute value returned.

    Example

    Let’s see an example, where we will pass a complex number through abs() function and get an absolute value.

    # complex number  
    
    complex_num = (5 + 12j)  
    
    #finding the absolute value using abs() function  
    
    print("Magnitude of complex number", complex_num,"is: ", abs(complex_num))

    Output:

    Magnitude of complex number (5+12j) is: 13.0

    Time-Distance Calculation Using Python abs() Function

    As we already know, the abs() function returns the positive value, and we are also aware that speed, distance, and time can’t be negative. So, we can use the abs() method to calculate the exact time, distance, and speed.

    The formula we are going to use is as follows:

    1. Distance  = Speed * Time  
    2. Time = Distance / Speed  
    3. Speed = Distance / Time  

    Example

    # Functions for basic motion calculations  
    
    # Calculate speed  
    
    def find_speed(distance, hours):  
    
        print("Distance (km):", distance)  
    
        print("Time (hr):", hours)  
    
        speed = distance / hours  
    
        return speed  
    
    # Calculate distance  
    
    def find_distance(rate, hours):  
    
        print("Speed (km/hr):", rate)  
    
        print("Time (hr):", hours)  
    
        distance = rate * hours  
    
        return distance  
    
    # Calculate time  
    
    def find_time(distance, rate):  
    
        print("Distance (km):", distance)  
    
        print("Speed (km/hr):", rate)  
    
        time_required = distance / rate  
    
        return time_required  
    
    # Main Program  
    
    # Using absolute values to avoid negative inputs  
    
    print("Calculated Speed (km/hr):",  
    
          find_speed(abs(46.2), abs(-2.0)))  
    
    print()  
    
    print("Calculated Distance (km):",  
    
          find_distance(abs(-60.5), abs(3.0)))  
    
    print()  
    
    print("Calculated Time (hr):",  
    
          find_time(abs(50.0), abs(5.0)))

    Output:

    Distance (km): 46.2
    Time (hr): 2.0
    Calculated Speed (km/hr): 23.1
    
    Speed (km/hr): 60.5
    Time (hr): 3.0
    Calculated Distance (km): 181.5
    
    Distance (km): 50.0
    Speed (km/hr): 5.0
    Calculated Time (hr): 10.0
    

    Exception of the abs() Function

    We cannot use any other data type except numerical ones with the abs() function.

    Let’s see what happens when we use a string with the abs() function.

    Example

    abs("PythonApp")  

    Output:

    ---------------------------------------------------------------------------
    TypeError Traceback (most recent call last)
    Cell In[8], line 1
    ----> 1 abs("TpoinTech")
    
    TypeError: bad operand type for abs(): 'str'
    

    It clearly defines that the abs() function can’t be used with any other data type, as it would result in an error.

    Conclusion

    The Python abs() function is used to return the absolute value of a number. The absolute function returns a positive number if the original number is negative. The syntax is abs(number). We discussed the abs() function using integer arguments, floating-point numbers, and complex numbers. We also learnt how to do Time-Distance calculation using the Python abs() Function.

  • Tower of Hanoi Puzzle Using Python

    The Tower of Hanoi is a mathematical function introduced in 1883 by the French mathematician Edouard Lucas. It consists of three towers (pegs) and two or more disks (as shown in the image below).

    The disks can be of different sizes, and they are arranged in a decreasing order, which means the largest disk is placed at the bottom, the smaller one in the middle and the smallest of the three at the top. In this example, we have taken three disks, but the disk count can increase or decrease; however, the tower count has to be 3.

    Rules of the Game

    The goal of the puzzle is to move all the disks to another tower without disturbing the sequence of arrangement i.e., the largest disk stacked at the bottom and the smallest one on top.

    Following are the rules to be followed for Tower of Hanoi:

    • Only one disk can be moved at a time.
    • You can only remove the upper disk.
    • No large disk can be placed on top of a small disk.

    Given below is the step-to-step illustration to solve a Tower of Hanoi puzzle with three disks.

    Step 0: All the disks are placed on the rod in an ascending order.

    Step 1: We will move the top disk to the middle tower.

    Step 2: Next, we will move the middle disk to the third tower. As a result, we will have one disks in each rod.

    Step 3: Move the disk from the second tower to the third tower.

    Step 4: Will move the first disk form tower one to tower two.

    Step 5: Again will move the top disk from tower 3 to tower 1.

    Step 6: Next shift the disk from tower 3 to the top of tower 2.

    Step 7: The last step would be to move the disk from tower 1 to the top of tower 2.

    As a result, we have successfully shifted all the disks from one tower to another abiding all the rules.

    In the Tower of Hanoi puzzle, the number of moves can be calculated using 2n – 1 steps (where n represents the disks).

    In our case, since we have 3 disks, the above formula will be calculated as 23 – 1 = 7 steps.

    Algorithm to Solve Tower of Hanoi

    The algorithm for Tower of Hanoi is very easy if you initially understand the logic to 1 disks, 2 disks and at last move 3 disks at a time. We have named the three towers as sourcetarget and aux (these names are temporarily given to track the disk movement among different towers easily).

    For 1 disk:

    It can move around the towers very easily. It can be moved from the source to the destination peg.

    For 2 disks:

    • Since we can only move the top disk, we will move it to the aux peg.
    • Next, we will move the bottom disk to the target peg.
    • The last step would be to move the smaller disk from the aux peg to the target peg.

    For 3 disks:

    Since we already understood the logic for moving one disk and two disks, we can easily conclude the algorithm for the Tower of Hanoi with three disks. We will conclude it in two parts. The bottom disk (nth or the largest disk) would be the first part, and all other disks (n-1) would be solved in the second part.

    The goal is to shift disk n (the largest disk) from source to target and resemble all other (n-1) disks onto it. We can imagine to apply the same in a recursive way for all given set of disks.

    Following are the steps:

    • Create a tower_of_hanoirecursive function and pass two arguments: the number of disks n and the name of the rods such as source, aux, and target.
    • We can define the base case when the number of disks is 1. In this case, simply move the one disk from the source to target and return.
    • Now, move remaining n-1 disks from source to auxiliary using the target as the auxiliary.
    • After that, the remaining 1 disk move on the source to target.
    • Move the n-1 disks on the auxiliary to the target using the source as the auxiliary.

    Python Program to implement Tower of Hanoi

    The following example is the implementation of Tower of Hanoi Puzzle using Python programming language:

    Example

    # Creating a recursive function    
    
    def tower_of_hanoi(disks, source, auxiliary, target):    
    
        if(disks == 1):    
    
            print('Move disk 1 from rod {} to rod {}.'.format(source, target))    
    
            return    
    
        # function call itself    
    
        tower_of_hanoi(disks - 1, source, target, auxiliary)    
    
        print('Move disk {} from rod {} to rod {}.'.format(disks, source, target))    
    
        tower_of_hanoi(disks - 1, auxiliary, source, target)    
    
        
    
        
    
    disks = int(input('Enter the number of disks: '))    
    
    # We are referring source as A, auxiliary as B, and target as C    
    
    tower_of_hanoi(disks, 'A', 'B', 'C')  # Calling the function

    Output:

    Enter the number of disks: 3
    Move disk 1 from rod A to rod C.
    Move disk 2 from rod A to rod B.
    Move disk 1 from rod C to rod B.
    Move disk 3 from rod A to rod C.
    Move disk 1 from rod B to rod A.
    Move disk 2 from rod B to rod C.
    Move disk 1 from rod A to rod C.
    

    Explanation:

    In this example, we have solve the Tower of Hanoi problem using a recursive function. It moves a specified number of disks from the source rod ‘A’ to the target rod ‘C’, using rod ‘B’ as an auxiliary. The function ensures only one disk moves at a time and maintains the order.

    Conclusion

    The Tower of Hanoi puzzle is a perfect example to show how recursion can be used in programming. In this tutorial, we have covered all the important details of the puzzle, its simple yet strict rules, and implemented the recursive solution using Python. By breaking down the problem into smaller subproblems, we were able to solve the entire puzzle step-by-step.

    There is no limit to learning. Therefore, don’t stop here, you can try the logic of this program of higher number disks and observe how the number of steps increases with it.

  • Second Largest Number in Python

    When we have a lot of elements in our list, the thought of finding the highest or lowest element can come to our mind and Python has made it much easier for us.

    In this article, we shall how we can use to find the second largest number in Python from a list.

    1. Sorting the list and then print the second last number.
    2. Removing the maximum element.
    3. Finding the maximum element.
    4. Traversing the list.

    Here, we are going to these discuss these examples one by one.

    Sorting the list and then print the second last number

    Let us take an example to illustrates how we can sort the list and then print the second last number in Python.

    Example:

    #program to find the second largest number of list  
    
    # declaring the list  
    
    list_val = [20, 30, 40, 25, 10]  
    
    # sorting the list  
    
    list_val.sort()  
    
    #displaying the second last element of the list  
    
    print("The second largest element of the list is:", list_val[-2])

    Output:

    The second largest element of the list is: 30
    

    It’s time to go for the explanation part-

    1. We have declared the list from which we want to take out the second last element.
    2. After this, we used the sort method so that all the elements of our list are arranged in ascending order.
    3. Now we make use of negative indexing since the second-largest number will come at the second last position.

    Removing the maximum element

    The second method is to obtain the second largest element of the list by removing the maximum element. Let us take an example to demonstrate how to remove the maximum element in Python.

    Example:

    #program to find the second largest number of list  
    
      
    
    # declaring the list  
    
    list_val = [20, 30, 40, 25, 10]  
    
      
    
    # new_list is a set of list1  
    
    res_list = set(list_val)  
    
      
    
    #removing the maximum element  
    
    res_list.remove(max(res_list))  
    
      
    
    #printing the second largest element   
    
    print(max(res_list))

    Output:

    30
    

    Explanation:

    Let us understand what we have done in the above program-

    1. We have declared the list from which we want to take out the second last element.
    2. After this, we used the set method to take all the unique elements of the list.
    3. Now we make use of max() to get the maximum value from the list and then remove it.
    4. After this, we print the maximum of the resultant list which will give us the second-largest number.

    Finding the Maximum Element

    In the third method, we will use for loop and find the second largest number from the list. Let us consider an example to demonstrate how to find the maximum number in Python.

    Example:

    # declaring empty list  
    
    list_val = []  
    
      
    
    # user provides the number of elements to be added in the list  
    
    num_list = int(input("Enter number of elements in list: "))  
    
      
    
      
    
    for i in range(1, num_list + 1):  
    
        element = int(input("Enter the elements: "))  
    
        list_val.append(element)  
    
      
    
      
    
    # sort the list  
    
    list_val.sort()  
    
          
    
    # print second largest element  
    
    print("Second largest element is:", list_val[-2])

    Output:

    Enter number of elements in list: 5
    
    Enter the elements: 10
    
    Enter the elements: 20
    
    Enter the elements: 30
    
    Enter the elements: 40
    
    Enter the elements: 50
    The second largest element is: 40
    

    Explanation:

    Let us have a glance at what we have done here-

    1. We have declared an empty list in which we will insert the elements.
    2. After this, we ask the user to provide us the number of elements we would like to add to our list.
    3. After this, we use the sort method so that all the elements of our list are arranged in ascending order.
    4. Now we make use of negative indexing since the second-largest number will come at the second last position.

    Traversing the list

    In the last program, we will traverse the list to find out the largest number and then make use of conditional statements to find the second largest number from the list. Now, let’s take an example to demonstrate how to traverse the list in Python.

    Example:

    def calc_largest(arr):  
    
        second_largest = arr[0]  
    
        largest_val = arr[0]  
    
        for i in range(len(arr)):  
    
            if arr[i] > largest_val:  
    
                largest_val = arr[i]  
    
      
    
        for i in range(len(arr)):  
    
            if arr[i] > second_largest and arr[i] != largest_val:  
    
                second_largest = arr[i]  
    
      
    
        return second_largest  
    
    print(calc_largest([20, 30, 40, 25, 10]))

    Output:

    30
    

    Explanation:

    Let us understand what we have done in the above program-

    1. The first step is to create a function that checks the largest number from the list by traversing it.
    2. In the next for loop, we traverse the list again for finding the highest number but this time excludes the previous one since here our objective is to find the second largest function.
    3. Finally, we pass our list in the function.

    Conclusion

    In this article, we got the chance to think out of the box and discover some new ways to develop the logic for finding the second largest number in Python.

  • Python SimpleImputer module

    In Python, a scikit-learn class that we can use to handle the missing values in the data from the dataset of a predictive model is called SimpleImputer class. With the help of this class, we can replace NaN (missing values) values in the dataset with a specified placeholder. We can implement and use this module class by using the SimpleImputer() method in the program.

    Syntax for SimpleImputer() method:

    In order to implement the SimpleImputer() class method into a Python program, we have to use the following syntax:

    SimpleImputer(missingValues, strategy)  

    Parameters:

    Following are the parameters which has to be defined while using the SimpleImputer() method:

    1. missingValues: It is the missing values placeholder in the SimpleImputer() method which has to be imputed during the execution, and by default, the value for missing values placeholder is NaN.
    2. strategy: It is the data that is going to replace the missing values (NaN values) from the dataset, and by default, the value method for this parameter is ‘Mean’. The strategy parameter of the SimpleImputer() method can take ‘Mean’, ‘Mode’, Median’ (Central tendency measuring methods) and ‘Constant’ value input in it.
    3. fillValue: This parameter is used only in the strategy parameter if we give ‘Constant’ as replacing value method. We have to define the constant value for the strategy parameter, which is going to replace the NaN values from the dataset.

    SimpleImputer class is the module class of Sklearn library, and to use this class, first we have to install the Sklearn library in our system if it is not present already.

    Installation of Sklearn library

    We can install the Sklearn by using the following command inside the command terminal prompt of our system:

    pip install sklearn  

    After pressing the enter key, the sklearn module will start installing in our device, as we can see below:

    Python SimpleImputer module

    Now, the Sklearn module is installed in our system, and we can move ahead with the SimpleImputer class function.

    Handling NaN values in the dataset with SimpleImputer class

    Now, we will use the SimpleImputer class in a Python program to handle the missing values present in the dataset (that we will use in the program). We will define a dataset in the example program while giving some missing values in it, and then we use the SimpleImputer class method to handle those values from the dataset by defining its parameters. Let’s understand the implementation of this through an example Python program.

    Python Example to Handle NaN values in the dataset with Simplelmputer class

    Look at the following Python program with a dataset having NaN values defined in it:

    # Import numpy module as nmp  
    
    import numpy as nmp  
    
    # Importing SimpleImputer class from sklearn impute module  
    
    from sklearn.impute import SimpleImputer  
    
    # Setting up imputer function variable  
    
    imputerFunc = SimpleImputer(missing_values = nmp.nan, strategy ='mean')  
    
    # Defining a dataset  
    
    dataSet = [[32, nmp.nan, 34, 47], [17, nmp.nan, 71, 53], [19, 29, nmp.nan, 79], [nmp.nan, 31, 23, 37], [19, nmp.nan, 79, 53]]  
    
    # Print original dataset  
    
    print("The Original Dataset we defined in the program: \n", dataSet)  
    
    # Imputing dataset by replacing missing values  
    
    imputerFunc = imputerFunc.fit(dataSet)  
    
    dataSet2 = imputerFunc.transform(dataSet)  
    
    # Printing imputed dataset  
    
    print("The imputed dataset after replacing missing values from it: \n", dataSet2)

    Output:

    The Original Dataset we defined in the program:
    [[32, nan, 34, 47], [17, nan, 71, 53], [19, 29, nan, 79], [nan, 31, 23, 37], [19, nan, 79, 53]]
    The imputed dataset after replacing missing values from it:
    [[32. 30. 34. 47. ]
    [17. 30. 71. 53. ]
    [19. 29. 51.75 79. ]
    [21.75 31. 23. 37. ]
    [19. 30. 79. 53. ]]
    

    Explanation:

    We have firstly imported the numpy module (to define a dataset) and sklearn module (to use the SimpleImputer class method) into the program. Then, we defined the imputer to handle the missing values using the SimpleImputer class method, and we used the ‘mean’ strategy to replace the missing values from the dataset. After that, we have defined a dataset in the program using the numpy module function and gave some missing values (NaN values) in the dataset. Then, we printed the original dataset in the output. After that, we have imputed and replaced the missing values from the dataset with the imputer that we have defined earlier in the program with SimpleImputer class. After imputing the dataset and replacing the missing values from it, we have printed the new dataset as a result.

    As we can see in the output, the imputed value dataset having mean values in the place of missing values, and that’s how we can use the SimpleImputer module class to handle NaN values from a dataset.

    Conclusion

    We have read about the SimpleImputer class method in this method, and we learned how we could use it to handle the NaN values present in a dataset. We learned about the strategy value parameter, which we use to define the method for replacing the NaN values of the dataset. We have also learned about the installation of the Sklearn library, and then last, we used the SimpleImputer class method in an example to impute the dataset.

  • Python OpenCV object detection

    OpenCV is the huge and open-source library for image processing, machine learning and computer vision. It is also playing an important role in real-time operation. With the help of the OpenCV library, we can easily process the images as well as videos to identify the objects, faces or even handwriting of a human present in the file. We will only focus to object detection from images using OpenCV in this tutorial. We will learn about how we can use OpenCV to do object detection from a given image using a Python program.

    Object Detection

    Basically, object detection is a modern computer technology that is related to image processing, deep learning and computer vision to detect the objects present in an image file. All the technologies used in the Object detection technique (as we mentioned earlier) deals with detecting instances of the object in the image or video.

    Object Detection using OpenCV

    We have learned about object detection in the previous section, and in this section, we will learn that how we can do object detection in an image or video using the OpenCV library. We will first import the OpenCV library in the Python program, and then we will use functions to perform object detection on an image file given to us. But, before using and importing the library functions, let’s first install the requirements for using the Object detection technique.

    In this tutorial, we will use the Haar cascade technique to do object detection. Let’s learn in brief about the Haar cascade technique first.

    Haar cascade

    Basically, the Haar cascade technique is an approach based on machine learning where we use a lot of positive and negative images to train the classifier to classify between the images. Haar cascade classifiers are considered as the effective way to do object detection with the OpenCV library. Now, let’s understand the concept of positive and negative images that we have discussed earlier:

    • Positive images: These are the images that contain the objects which we want to be identified from the classifier.
    • Negative Images: These are the images that do not contain any object that we want to be detected by the classifier, and these can be images of everything else.

    Requirements for object detection with Python OpenCV:

    We have to install first some important libraries in our system as it is an important requirement for doing object detection tasks. We have to install the following libraries into our system as the requirement for performing object detection:

    1. Installation of OpenCV library:

    First and foremost, the requirement to perform object detection using the OpenCV library is that the OpenCV library should be present in our device so that we can import it into a Python program and use its object detection functions. If this library is not present in our system, we can use the following command in our command prompt terminal to install it:

    pip install opencv-python  
    Python OpenCV object detection

    When we press the enter key after writing this command in the terminal, the pip installer in the command prompt will start installing the OpenCV library into our system.

    Python OpenCV object detection

    As we can see that, the OpenCV library is successfully installed in our system, and now we can import it into a Python program to use its functions.

    2. Installation of matplotlib library:

    Matplotlib is very helpful in the opening, closing, reading etc., images in a Python program, and that’s why the installation of this library for object detection becomes an important requirement. If the matplotlib library is not present in our system, we have to use the following command in our command prompt terminal to install it:

    pip install matplotlib  
    Python OpenCV object detection

    When we press the enter key after writing this command in the terminal, the pip installer in the command prompt will start installing it into our system.

    Python OpenCV object detection

    As we can see that, the matplotlib library is successfully installed in our system, and now we can import it into a Python program to use its functions for opening, reading etc., images.

    We have installed all the required libraries for performing object detection, and now we can move ahead with the implementation part of this task.

    Implementation of Object detection in Python:

    In this part, we will write the Python programs to do the object detection and understand the implementation of it. We will use the following image in our Python program to perform the object detection on it:

    Python OpenCV object detection

    Opening the Image

    We will first open the image given above and create the environment of the picture to show it in the output. Let’s first look at an example program to understand the implementation, and then we will look at the explanation part.

    Example 1: Opening the image using OpenCV and matplotlib library in a Python program:

    # Import OpenCV module  
    
    import cv2  
    
    # Import pyplot from matplotlib as pltd  
    
    from matplotlib import pyplot as pltd  
    
    # Opening the image from files  
    
    imaging = cv2.imread("opencv-od.png")  
    
    # Altering properties of image with cv2  
    
    img_gray = cv2.cvtColor(imaging, cv2.COLOR_BGR2GRAY)  
    
    imaging_rgb = cv2.cvtColor(imaging, cv2.COLOR_BGR2RGB)  
    
    # Plotting image with subplot() from plt  
    
    pltd.subplot(1, 1, 1)  
    
    # Displaying image in the output  
    
    pltd.imshow(imaging_rgb)  
    
    pltd.show()

    Output:

    Python OpenCV object detection

    Explanation:

    First, we have imported the OpenCV (as cv2) and matplotlib (as plt) libraries into the program to use their functions in the code. After that, we have opened the image file using the imread() function of cv2.

    Then, we have defined the properties for the image we opened in the program using the cv2 functions. Then, we subplot the image using the subplot() function of plt and giving parameters in it. In last, we have used the imshow() and show() function of the plt module to show the image in the output.

    As we can see in the output, the image is displayed as a result of the program, and its borders have been sub-plotted.

    Recognition or object detection in the image

    Now, we will use the detectMultiScale() in the program to detect the object present in the image. Following is the syntax for using detectMultiScale() function in the code:

    found = xml_data.detectMultiScale(img_gray,   
    
                                       minSize = (30, 30))

    We will use a condition statement with this function in the program to check if any object from the image is detected or not and highlight the detected part. Let’s understand the implementation of object detection in the image through an example program.

    Example 2: Object detection in the image using the detectMultiScale() in the following Python program:

    # Import OpenCV module  
    
    import cv2  
    
    # Import pyplot from matplotlib as plt  
    
    from matplotlib import pyplot as pltd  
    
    # Opening the image from files  
    
    imaging = cv2.imread("opencv-od.png")  
    
    # Altering properties of image with cv2  
    
    imaging_gray = cv2.cvtColor(imaging, cv2.COLOR_BGR2GRAY)  
    
    imaging_rgb = cv2.cvtColor(imaging, cv2.COLOR_BGR2RGB)  
    
    # Importing Haar cascade classifier xml data  
    
    xml_data = cv2.CascadeClassifier('XML-data.xml')  
    
    # Detecting object in the image with Haar cascade classifier   
    
    detecting = xml_data.detectMultiScale(imaging_gray,   
    
                                       minSize = (30, 30))  
    
    # Amount of object detected  
    
    amountDetecting = len(detecting)  
    
    # Using if condition to highlight the object detected  
    
    if amountDetecting != 0:  
    
        for (a, b, width, height) in detecting:  
    
            cv2.rectangle(imaging_rgb, (a, b), # Highlighting detected object with rectangle  
    
                          (a + height, b + width),   
    
                          (0, 275, 0), 9)  
    
    # Plotting image with subplot() from plt  
    
    pltd.subplot(1, 1, 1)  
    
    # Displaying image in the output  
    
    pltd.imshow(imaging_rgb)  
    
    pltd.show()

    Output:

    Python OpenCV object detection

    Explanation:

    After opening the image in the program, we have imported the cascade classifier XML file into the program. Then, we used the detectMultiScale() function with the imported cascade file to detect the object present in the image or not.

    We used if condition in the program to check that object is detected or not, and if the object is detected, we have highlighted the detected object part using for loop with cv2 functions. After highlighting the detected object part in the image, we have displayed the processed image using the plt show() and imshow() function.

    As we can see in the output, the image with the object detected part as highlighted is shown to us when we run the program.

  • Python program to find the nth Fibonacci Number

    In the following tutorial, we will understand how to find the nth Fibonacci Number using Python. We can define a Fibonacci Number, where the following number is the sum of the preceding two numbers.

    The first two elements of the Fibonacci series are 0 and 1, respectively. We can calculate the third element of the series by adding the preceding two elements and will get the third term as 0 + 1, which is equal to 1. Similarly, the fourth term will be the sum of the second and third terms, which is 1 + 1 = 2 and so on. The series of such numbers is known as a Fibonacci Series.

    The recurrence relation defines a Fibonacci number as shown below:

    Fn = Fn – 1 + Fn – 2

    There are different ways to find the nth Fibonacci Number using the Python programming language. Some of them are as follows:

    1. Finding nth Fibonacci Number using Recursion
    2. Finding nth Fibonacci Number using dynamic programming
    3. Finding nth Fibonacci Number using dynamic programming and space optimization
    4. Finding nth Fibonacci Number using arrays

    Of these ways, the two most fundamental are the Recursion method and the Dynamic method.

    Let us understand the working of these methods in detail with examples.

    Finding nth Fibonacci Number using Recursion

    The term recursion is used to define something within itself. In a programming language like Python, Recursion refers to the process of a function calling itself. With the proper and correct code, the Recursion will create a finite loop.

    Let us consider the following example to demonstrate how to find the nth Fibonacci Number using Recursion.

    Example:

    # defining the function for Fibonacci Series  
    
    def Fibonacci_Series(n):   
    
        # using if-else conditional statement  
    
        if n < 0:  
    
            print("Oops! Incorrect input")  
    
        # First Fibonacci number is 0  
    
        elif n == 0:   
    
            return (0)   
    
        # Second Fibonacci number is 1   
    
        elif n == 1:  
    
            return (1)  
    
        else:  
    
            return (Fibonacci_Series(n - 1) + Fibonacci_Series(n - 2))   
    
    # printing the 12th element of the Fibonacci Series  
    
    print("12th Element of the Fibonacci Series:", Fibonacci_Series(12))

    Output:

    12th Element of the Fibonacci Series: 144
    

    Explanation:

    In the above snippet of code, we have defined a function as Fibonacci_Series() that accepts a parameter as n.

    Moreover, we are aware that the first two elements of the Fibonacci are 0 and 1. In the event of the input as n = 1 or n = 2 (First or Second terms of Fibonacci series), we have used the if-else conditional statement to return 0 or 1. In case the value of n is greater than 2, the function will call itself with a lower input value. As we can observe that the code returns (Fibonacci_Series(n – 1) + Fibonacci_Series(n – 2)). Here, the function calls itself with a lower value unless it reaches the base value of n = 1 and n = 2, and as we know from before, n = 1 returns 0 and n = 2 returns 1. The returned values are then continuously added to produce the sequence of the Fibonacci Series.

    Finding the nth Fibonacci Number using Dynamic Programming

    Dynamic Programming utilizes Recursion as well; however, it mainly utilizes if-else conditional statements. Within the statements, the value of the Fibonacci number is stored in a variable. With the help of Recursion, the repeated addition allows us to obtain this Fibonacci number.

    Let us consider the following example to understand how to find the nth Fibonacci Number using Dynamic Programming.

    Example:

    # defining the function to find the nth Fibonacci Number  
    
    def Fibonacci_series(x):  
    
        # Taking First two terms of the Fibonacci Series as 0 and 1  
    
        fib_Array = [0, 1]  
    
        # Here, as we know that the first two terms of Fibonacci Series are 0 and 1,  
    
        # we append the remaining values (Fibonacci numbers from index 2 to x)  
    
        # in the array using recursion and return the last element.   
    
        # In the range function, we take range(2, x + 1) instead of range(2, x).  
    
        # This is because range function in python iterates until the value  
    
        # before the upper limit. So, if we take from 2 to x, it would only  
    
        # iterate from second to (x - 1)th element.  
    
        for n in range(2, x + 1):  
    
            fib_Array.append(fib_Array[n - 1] + fib_Array[n - 2])  
    
        return fib_Array[x]  
    
    print("12th Term of Fibonacci Series:", Fibonacci_series(12))

    Output:

    12th Term of Fibonacci Series: 144
    

    Explanation:

    In the above snippet of code, we defined the function as Fibonacci_series(), which accepts the parameter as variable x. We created a one-dimensional array as fib_Array with data elements 0 and 1 in its zeroth and first indices. Then, if the provided input (‘x‘) is less than or equal to 2, which is also the length of the array fib_Array, it returns 0 as the first number for x = 1 and 1 as the second number for x = 2. If the value of x is greater than 2, we have used recursion to call and insert the preceding two data elements. However, rather than returning the nth Fibonacci number directly, we append each of the summated elements to the fib_Array array. At last, we have returned the last element of the array (i.e., the nth element) and printed the value for the users.

    Finding the nth Fibonacci Number using Dynamic Programming and Space Optimization

    This method is almost completely identical to Dynamic Programming. However, dynamic programming utilizes recursion to accomplish recurring addition, whereas this method utilizes the for-loop.

    Let us consider the following example to understand how to find the nth Fibonacci Number using Dynamic Programming and Space Optimization.

    Example:

    # defing the function to return the nth element of the Fibonacci Series  
    
    def Fibonacci_series(x):   
    
        # assiging the variables  
    
        m = 0  
    
        n = 1  
    
        # using the if-elif-else conditional statements  
    
        if x < 0:  
    
            print("Wrong input")   
    
        elif x == 0:  
    
            return m   
    
        elif x == 1:   
    
            return n  
    
        else:  
    
            # using the for-loop   
    
            for i in range(2, x + 1):   
    
                o = m + n  
    
                m = n   
    
                n = o   
    
            return n   
    
    # printing the twelveth term of the Fibonacci Series  
    
    print("12th element of the Fibonacci Series:", Fibonacci_series(12))

    Output:

    12th element of the Fibonacci Series: 144
    

    Explanation:

    In the above snippet of code, we have defined a function and assigned two variables, m = 0 and n = 1. These elements are the first and second elements of the Fibonacci Series. We have then used the if-elif-else conditional statements where the program returns 0 for input value x = 1 and 1 for input value x = 2. If the value of x is greater than 2, we have used the for-loop of i in the range (2, x + 1). We have taken a variable o to store the sum of the preceding two elements in the series. Once o takes the value of m + n, the value of m is reassigned to n. Subsequently, the value of n is reassigned to the value of o. This process continues, and value 3 keeps reassigning until the loop terminates. Once the loop is terminated, the function returns the value of n, which stores the value of the nth Fibonacci Number.

    Finding the nth Fibonacci Number using Array

    In this method, we create an array of size x by repeated addition using the for-loop. Hence, the nth Fibonacci Number is returned.

    Let us consider the following example to understand how to find the nth Fibonacci Number using Arrays.

    Example:

    # defining the function  
    
    def Fibonacci_series(x):   
    
      # creating an array in the function  
    
       fib_Array = [0] * (x + 1)  
    
       fib_Array[1] = 1  
    
       # adding elements of the series to the array using addition of previous two elements.  
    
       for n in range (2, x + 1):  
    
          fib_Array[n] = fib_Array[n - 1] + fib_Array[n - 2]   
    
       return fib_Array[x]  
    
    if __name__ == "__main__":  
    
       print("12th element of the Fibonacci series:", Fibonacci_series(12))

    Output:

    12th element of the Fibonacci series: 144
    

    Explanation:

    In the above snippet of code, we have defined the function. Within the function, we have created an array to find the nth element of the Fibonacci Series. We have then used the for-loop to add elements of the series to the array by repeating the addition of the preceding two elements. At last, the nth element is returned and printed for the users.

  • nsetools in Python

    Python offers a library that allows programmers to collect real-time data from the National Stock Exchange (India). This library is known as nsetools. We can use this library in different projects that require fetching live quotes for a provided index or stock, or creating large sets of data for further data analytics.

    We can also create Command-Line Interface (CLI) Applications that may deliver us the details of the live market at a blazing fast speed, faster than any web browser. The data accuracy is only as correct as provided on the official website of the National Stock Exchange of India Limited.

    Features of the Python nsetools library

    Some of the key features of the Python nsetools library are stated as follows:

    • The nsetools library works out of the box, without any setup requirements.
    • This library helps programmers to fetch livestock code and index codes at blazing fast speed.
    • It also offers a set of all stocks and indices traded on the National Stock Exchange.

    Moreover, it also provides a set of:

    • Top losers
    • Top gainers
    • Most active

    It also delivers several helpful Application Programming Interfaces (APIs) in order to validate a stock code and index code.

    • The library optionally returns data in JSON
    • It has a hundred percent Unit test coverage.

    Installing Python nsetools library

    The installation part of the nsetools library is quite easy, and it has no external dependencies. All the dependencies of the library are part of the standard distribution packages of Python. We can install the nsetools library using the pip installer as shown in the following syntax:

    Command:

    pip install nsetools  

    Updating the library

    If some of us have already installed the nsetools library in their systems, then the following command will allow them to update the library.

    pip install nsetools -upgrade  

    Python 3 support

    Python 3 support for the library has been included from version 1.0.0 and so on. Now, this library is able to work for both Python 2 and Python 3.

    Creating an NSE object

    We can create an NSE object using the Nse() function offered by the nsetools library. The same can be seen in the following example:

    Example:

    # importing the Nse() function from the nsetools library    
    
    from nsetools import Nse    
    
        
    
    # creating an NSE object    
    
    nse-obj = Nse()    
    
        
    
    # printing the value of the object    
    
    print("NSE Object:", nse-obj)

    Output:

    NSE Object: Driver Class for National Stock Exchange (NSE)

    Explanation:

    In the above snippet of code, we have imported the required function from the library. We have then defined a variable that uses the Nse() function to create an NSE object. We have then printed the value of the variable for the users.

    Getting Information using the nsetools library

    Let us consider an example demonstrating the use of nsetools for gathering Information.

    from nsepython import nse-eq  
    
      
    
    # Get quote for State Bank of India (SBIN)  
    
    data = nse-eq("SBIN")  
    
      
    
    # Print the whole structure (to explore available fields)  
    
    print(data)  
    
      
    
    # Extract useful information  
    
    print("Company Name:", data.get("info", {}).get("companyName", "Not Available"))  
    
    print("Symbol:", data.get("info", {}).get("symbol", "Not Available"))  
    
    print("Last Price:", data.get("priceInfo", {}).get("lastPrice", "Not Available"))  
    
    print("Average Price:", data.get("priceInfo", {}).get("averagePrice", "Not Available"))

    Output:

    {'info': {'symbol': 'SBIN', 'companyName': 'State Bank of India', 'industry': 'Public Sector Bank', 'activeSeries': ['EQ', 'T0'], 'debtSeries': [], 'isFNOSec': True, 'isCASec': False, 'isSLBSec': True, 'isDebtSec': True, 'isSuspended': False, 'tempSuspendedSeries': ['N1', 'N4', 'N3', 'IL', 'N5', 'N6', 'N2'], 'isETFSec': False, 'isDelisted': False, 'isin': 'INE062A01020', 'slb-isin': 'INE062A01020', 'listingDate': '1995-03-01', 'isMunicipalBond': False, 'isHybridSymbol': False, 'isTop10': False, 'identifier': 'SBINEQN'}, 'metadata': {'series': 'EQ', 'symbol': 'SBIN', 'isin': 'INE062A01020', 'status': 'Listed', 'listingDate': '01-Mar-1995', 'industry': 'Public Sector Bank', 'lastUpdateTime': '10-Sep-2025 11:58:56', 'pdSectorPe': 9.22, 'pdSymbolPe': 9.22, 'pdSectorInd': 'NIFTY 50', 'pdSectorIndAll': ['NIFTY 50', 'NIFTY BANK', 'NIFTY FINANCIAL SERVICES', 'NIFTY FINANCIAL SERVICES 25/50', 'NIFTY500 MULTICAP 50:25:25', 'NIFTY TOTAL MARKET', 'NIFTY HOUSING', 'NIFTY200 VALUE 30', 'NIFTY SERVICES SECTOR', 'NIFTY TOP 15 EQUAL WEIGHT', 'NIFTY RURAL', 'NIFTY500 LARGEMIDSMALL EQUAL-CAP WEIGHTED', 'NIFTY DIVIDEND OPPORTUNITIES 50', 'NIFTY TOP 20 EQUAL WEIGHT', 'NIFTY PSU BANK', 'NIFTY500 EQUAL WEIGHT', 'NIFTY 200', 'NIFTY 100', 'NIFTY100 LIQUID 15', 'NIFTY100 ESG', 'NIFTY 500', 'NIFTY INDIA FPI 150', 'NIFTY HIGH BETA 50', 'NIFTY500 LOW VOLATILITY 50', 'NIFTY100 ENHANCED ESG', 'NIFTY500 VALUE 50', 'NIFTY LARGEMIDCAP 250', 'NIFTY100 EQUAL WEIGHT', 'NIFTY50 EQUAL WEIGHT', 'NIFTY50 VALUE 20']}, 'securityInfo': {'boardStatus': 'Main', 'tradingStatus': 'Active', 'tradingSegment': 'Normal Market', 'sessionNo': '-', 'slb': 'Yes', 'classOfShare': 'Equity', 'derivatives': 'Yes', 'surveillance': {'surv': None, 'desc': None}, 'faceValue': 1, 'issuedSize': 9230617586}, 'sddDetails': {'SDDAuditor': '-', 'SDDStatus': '-'}, 'currentMarketType': 'NM', 'priceInfo': {'lastPrice': 821.25, 'change': 12.399999999999977, 'pChange': 1.5330407368486094, 'previousClose': 808.85, 'open': 812, 'close': 0, 'vwap': 818.39, 'stockIndClosePrice': 0, 'lowerCP': '728.00', 'upperCP': '889.70', 'pPriceBand': 'No Band', 'basePrice': 808.85, 'intraDayHighLow': {'min': 810.4, 'max': 824.6, 'value': 821.25}, 'weekHighLow': {'min': 680, 'minDate': '03-Mar-2025', 'max': 875.45, 'maxDate': '06-Dec-2024', 'value': 821.25}, 'iNavValue': None, 'checkINAV': False, 'tickSize': 0.05, 'ieq': ''}, 'industryInfo': {'macro': 'Financial Services', 'sector': 'Financial Services', 'industry': 'Banks', 'basicIndustry': 'Public Sector Bank'}, 'preOpenMarket': {'preopen': [{'price': 810.05, 'buyQty': 350, 'sellQty': 0}, {'price': 810.1, 'buyQty': 1005, 'sellQty': 0}, {'price': 810.55, 'buyQty': 50, 'sellQty': 0}, {'price': 811, 'buyQty': 1000, 'sellQty': 0}, {'price': 811.05, 'buyQty': 50, 'sellQty': 0}, {'price': 812, 'buyQty': 0, 'sellQty': 3258, 'iep': True}, {'price': 812.05, 'buyQty': 0, 'sellQty': 6}, {'price': 812.1, 'buyQty': 0, 'sellQty': 6}, {'price': 812.15, 'buyQty': 0, 'sellQty': 6}, {'price': 812.2, 'buyQty': 0, 'sellQty': 6}], 'ato': {'buy': 0, 'sell': 0}, 'IEP': 812, 'totalTradedVolume': 28875, 'finalPrice': 812, 'finalQuantity': 28875, 'lastUpdateTime': '10-Sep-2025 09:07:48', 'totalBuyQuantity': 78075, 'totalSellQuantity': 195898, 'atoBuyQty': 0, 'atoSellQty': 0, 'Change': 3.15, 'perChange': 0.39, 'prevClose': 808.85}}
    Company Name: State Bank of India
    Symbol: SBIN
    Last Price: 821.25
    Average Price: Not Available
    

    Explanation:

    In the above snippet of code, we have imported the required module and created an NSE object using the Nse() function. We have then defined another variable that uses the get-quote() function on the NSE object to get the quotation of the specified company. We have then printed the required details for the users.

  • Python High Order Function

    Prerequisites

    In order to learn about high order functions in Python, we must have basic knowledge of the following concepts:

    • Python functions
    • Parameters
    • Python objects
    • Python decorators

    First, let’s start with the first thing, i.e., High order functions, and understand a basic about them.

    High Order Functions

    A function that is having another function as an argument or a function that returns another function as a return in the output is called the High order function. High order functions operate with other functions given in the program.

    A fact about the High order function is that a high order function is applicable to both functions as well as to the methods that take a function as their parameter or return a function as the result of them. In Python, this concept of high-order functions is supported with every aspect.

    Properties of High order functions

    Now, we will discuss some of the important properties of high order functions that are applicable in Python as well.

    • In high order function, we can store a function inside a variable.
    • In high order function, a function can act as an instant of an object type.
    • In high order function, we can return a function as a result of another function.
    • In high order function, we can pass a function as a parameter or argument inside another function.
    • We can store Python high order functions in data structures format such as lists, hash tables, etc.

    Different Ways to Define High Order Function

    Following are the ways to define High order functions in a Python code that we are going to discuss in this tutorial.

    1. Using functions as objects in High order function
    2. Returning function as a result in high order function
    3. Functions as a parameter for another function
    4. Decorators as high order function

    Now, we will discuss each of the above-given methods in detail and learn about their implementation as high order functions in a Python program.

    Method 1: Using functions as objects in High order function

    In Python, we can even assign a given function to a variable also. This assignment of function into variable will not call the actual function, instead of it will create a reference to the function that is created. Thus, it makes this assignment of assigning a function as a variable object will create a high order function in the program.

    Look at the following example program to learn the implementation of method we discussed above:

    Example:

    # a default function to take another function parameter  
    
    def spell(text):  
    
        # Making text in upper  
    
        return text.upper()   
    
    # Taking text as user input  
    
    text = input("Enter a text to print it in uppercase and double: ")  
    
    # Spell function with text  
    
    print(spell(text))   
    
    # Assigning variable with the default function  
    
    scream = spell  
    
    # Scream with text variable  
    
    print(scream(text))

    Output:

    Enter a text to print it in uppercase and double: Python App
    Python App
    Python App

    Method 2: Functions as a parameter for another function

    Basically, Python functions are like Python objects, and therefore we can use Python functions to pass them as an argument inside another function, and that will create a high order function in the program.

    Look at the following program to understand the implementation of above-given method:

    Example:

    # Default function for making text uppercase  
    
    def scream(word):   
    
        return word.upper()   
    
    # Default function for making text lowercase  
    
    def spell(word):   
    
        return word.lower()   
    
    # A third function that work as a high order function  
    
    def speak(funct):   
    
        # Storing the function in a variable in high order function   
    
        speaking = funct("Hello Python Developers! You are welcomed to JavaTpoint")   
    
        print(speaking)    
    
    # Printing text in uppercase  
    
    speak(scream)  
    
    # Printing text in lowercase  
    
    speak(spell)

    Output:

    HELLO PYTHON DEVELOPERS! YOU ARE WELCOMED TO Python App
    hello python developers! you are welcomed to pythonapp

    Method 3: Returning function as a result in high order function

    We can also return a function as the result of another function as an object, and that makes the function a high order function.

    Look at the following example program to learn the implementation of method we discussed above:

    Example:

    # A default function for addition  
    
    def Adding(a):  
    
        # Nested function with second number   
    
        def Addition(b):   
    
                return a + b # addition of two numbers  
    
        return Addition # Result  
    
      
    
    # Taking both number variable as user input  
    
    a = int(input("Enter First Number: "))  
    
    b = int(input("Enter Second Number: "))  
    
    # Assigning nested adding function to a variable  
    
    AddVariable = Adding(a)  
    
    # Using variable as high order function  
    
    Result = AddVariable(b)  
    
    # Printing result  
    
    print("Sum of Two numbers given by you is: ", Result)

    Output:

    Enter First Number: 24
    Enter Second Number: 26
    Sum of Two numbers given by you is: 50
    

    Method 4: Decorators as high order function

    We can use decorators as the high order function as the most commonly used high order function in Python. Decorators in Python allow us to modify the behavior of methods or functions we defined in the program, and it also allows us to wrap a function inside another function to extend the behavior of wrapped or parent function. We can even wrap a function inside another function without even permanently modifying the parent function.

    In Python decorators, a function is taken as an argument for the other function, and then these decorators are called inside the wrapped function. Look at the following exemplar syntax for a decorator defined in a Python program.

    Syntax

    # Using a decorator  
    
    @JTP_Decorator  
    
    def Python_Decorator():   
    
        .  
    
        .

    The above syntax for the decorator is equivalent to the following Python code for a high order function.

    # Using Python default function as Python decorators  
    
    def Python_Decorator():   
    
        .  
    
        .  
    
    Python_Decorator = @JTP_Decorator(Python_Decorator)

    We have referred @JTP_Decorator as a callable function inside the default Python_Decorator() function in the above-given code. We will have to add just some extra code in this structure, and we will get the output as the wrapper function.

    Look at the following program to understand the implementation of above given method:

    Example:

    # Using default function as Python decorators  
    
    def Python_Decorator(funct):  
    
           # Inner nested function  
    
           def inner():   
    
                  print("This line of code will be printed before the execution of high order function")  
    
                  funct()   
    
                  print("This line of code will be printed after the execution of high order function")  
    
           return inner   
    
    # A default function as decorator  
    
    def JTP_Decorator():   
    
        print("This line of code will be printed inside the execution of high order function")  
    
    JTP_Decorator = Python_Decorator(JTP_Decorator) # Python decorator as high order function   
    
    # Python decorator calling out as high order function   
    
    JTP_Decorator()

    Output:

    This line of code will be printed before the execution of high order function
    This line of code will be printed inside the execution of high order function
    This line of code will be printed after the execution of high order function