Author name: Vikram Chiluka

Python Numpy matrix.argmin() Function

NumPy Library 

NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it into our program and then we can easily use the functionality of NumPy in our program.

NumPy is a Python library that is frequently used for scientific and statistical analysis. NumPy arrays are grids of the same datatype’s values.

Numpy matrix.argmin() Function:

Using the matrix.argmin() method of the Numpy module, we can obtain the index value of the smallest/minimum element in a given matrix including one or more dimensions.

Syntax:

 matrix.argmin()

Return Value:

The index value of the smallest/minimum element in a given matrix is returned by the argmin() Function.

Numpy matrix.argmin() Function in Python

For 2-Dimensional (2D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing some random 2D matrix as an argument to it and store it in a variable
  • Print the given matrix
  • Apply the argmin() function on the given matrix to get the index value of the minimum(smallest) element in a given matrix and store it in another variable
  • Print the index value of the smallest element in a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing 
# some random 2D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[10, 8; 3, 1]')

# Print the given matrix
print("The given matrix is:") 
print(gvn_matrx)   

# Apply the argmin() function on the given matrix to get the index value of the 
# minimum(smallest) element in a given matrix and store it in another variable
rslt = gvn_matrx.argmin()

# Print the index value of the smallest element in a given matrix 
print("The index of the smallest element in a given matrix = ", rslt)

Output:

The given matrix is:
[[10 8]
 [ 3 1]]
The index of the smallest element in a given matrix = 3

For 3-Dimensional (3D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing some random 3D matrix as an argument to it and store it in a variable
  • Print the given matrix
  • Apply the argmin() function on the given matrix to get the index value of the minimum(smallest) element in a given matrix and store it in another variable
  • Print the index value of the smallest element in a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing 
# some random 3D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[5, 6, 4; 2, 7, 8; 9, -1, 3]')

# Print the given matrix
print("The given matrix is:") 
print(gvn_matrx)   

# Apply the argmin() function on the given matrix to get the index value of the 
# minimum(smallest) element in a given matrix and store it in another variable
rslt = gvn_matrx.argmin()

# Print the index value of the smallest element in a given matrix 
print("The index of the smallest element in a given matrix = ", rslt)

Output:

The given matrix is:
[[ 5 6 4]
 [ 2 7 8]
 [ 9 -1 3]]
The index of the smallest element in a given matrix = 7

Python Numpy matrix.argmin() Function Read More »

Python Numpy matrix.argmax() Function

NumPy Library 

NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it into our program and then we can easily use the functionality of NumPy in our program.

NumPy is a Python library that is frequently used for scientific and statistical analysis. NumPy arrays are grids of the same datatype’s values.

Numpy matrix.argmax() Function:

Using the matrix.argmax() method of the Numpy module, we can obtain the index value of the largest/maximum element in a given matrix including one or more dimensions.

Syntax:

 matrix.argmax()

Return Value:

The index value of the largest/maximum element in a given matrix is returned by the argmax() Function.

Numpy matrix.argmax() Function in Python

For 2-Dimensional (2D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing some random 2D matrix as an argument to it and store it in a variable
  • Print the given matrix.
  • Apply the argmax() function on the given matrix to get the index value of the maximum (largest) element in a given matrix and store it in another variable
  • Print the index value of the largest element in a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing 
# some random 2D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[10, 8; 3, 1]')

# Print the given matrix
print("The given matrix is:") 
print(gvn_matrx)   

# Apply the argmax() function on the given matrix to get the index value of the 
# maximum(largest) element in a given matrix and store it in another variable
rslt = gvn_matrx.argmax()

# Print the index value of the largest element in a given matrix 
print("The index of the largest element in a given matrix = ", rslt)

Output:

The given matrix is:
[[10 8]
 [ 3 1]]
The index of the largest element in a given matrix = 0

For 3-Dimensional (3D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing some random 3D matrix as an argument to it and store it in a variable
  • Print the given matrix.
  • Apply the argmax() function on the given matrix to get the index value of the maximum (largest) element in a given matrix and store it in another variable
  • Print the index value of the largest element in a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing 
# some random 3D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[5, 6, 4; 2, 7, 8; 9, -1, 3]')

# Print the given matrix
print("The given matrix is:") 
print(gvn_matrx)   

# Apply the argmax() function on the given matrix to get the index value of the 
# maximum(largest) element in a given matrix and store it in another variable
rslt = gvn_matrx.argmax()

# Print the index value of the largest element in a given matrix 
print("The index of the largest element in a given matrix = ", rslt)

Output:

The given matrix is:
[[ 5 6 4]
 [ 2 7 8]
 [ 9 -1 3]]
The index of the largest element in a given matrix = 6

Python Numpy matrix.argmax() Function Read More »

Python sympy.Matrix.row_del() Method

Python SymPy Module:

SymPy is a Python symbolic mathematics library. It aims to be a full-featured computer algebra system (CAS) while keeping the code as basic(simple) as possible in order to be understandable and easily expandable. SymPy is entirely written in Python. SymPy is simple to use because it only depends on mpmath, a pure Python library for arbitrary floating-point arithmetic.

Rational and Integer are the numerical types defined by SymPy. A rational number is represented by the Rational class as a pair of two Integers, numerator and denominator, therefore Rational(1, 2) is 1/2, Rational(3, 2) is 3/2, and so on. Integer numbers are represented by the Integer class.

SymPy uses mpmath in the background, allowing it to execute arbitrary-precision arithmetic computations. Some special constants, such as exp, pi, and oo (Infinity), are thus considered as symbols and can be evaluated with arbitrary precision.

Installation:

pip install sympy

Python sympy.Matrix.row_del() Method:

We can delete the rows of a matrix using the sympy.Matrix.row_del() function.

Syntax:

 sympy.Matrix().row_del()

Return Value:

A new matrix after the deletion of the row is returned by the Matrix.row_del() function.

sympy.Matrix.row_del() Method in Python

For 2-Dimensional (2D) Matrix

Approach:

  • Import all the methods from sympy using the import keyword
  • Create a 2-Dimensional(2D) matrix using the Matrix() function by passing some random 2D matrix as an argument to it and store it in a variable.
  • Apply row_del() function on the above-given matrix by passing the row number as an argument to it
    to delete the values of the specified row.
  • Here it deletes the zero(0th) row.
  • Print the given matrix after deleting the zero(0th) row.
  • The Exit of the Program.

Below is the implementation:

# Import all the methods from sympy using the import keyword
from sympy import *

# Create a 2-Dimensional(2D) matrix using the Matrix() function by passing some random
# 2D matrix as an argument to it and store it in a variable.
gvn_matrx = Matrix([[3, 5], [6, 8]])
# Apply row_del() function on the above given matrix by passing the row number as an
# argument to it to delete the values of the specified row.
# Here it deletes the zero(0th) row.
gvn_matrx.row_del(0)

# Print the given matrix after deleting the zero(0th) row.
print("The given matrix after deleting the zero(0th) row:")
print(gvn_matrx)

Output:

The given matrix after deleting the zero(0th) row:
Matrix([[6, 8]])

For 3-Dimensional (3D) Matrix

Approach:

  • Import all the methods from sympy using the import keyword
  • Create a 3-Dimensional(3D) matrix using the Matrix() function by passing some random 3D matrix as an argument to it and store it in a variable.
  • Apply row_del() function on the above-given matrix by passing the row number as an argument to it
    to delete the values of the specified row.
  • Here it deletes the 1st row.
  • Print the given matrix after deleting the 1st row.
  • The Exit of the Program.

Below is the implementation:

# Import all the methods from sympy using the import keyword
from sympy import *

# Create a 3-Dimensional(3D) matrix using the Matrix() function by passing some random
# 3D matrix as an argument to it and store it in a variable.
gvn_matrx = Matrix([[1, 6, 10], [8, 7, 5], [3, 2, 9]])

# Apply row_del() function on the above given matrix by passing the row number as
# an argument to it to delete the values of the specified row.
# Here it deletes the 1st row
gvn_matrx.row_del(1)

# Print the given matrix after deleting the 1st row
print("The given matrix after deleting the 1st row:")
print(gvn_matrx)

Output:

The given matrix after deleting the 1st row:
Matrix([[1, 6, 10], [3, 2, 9]])

Python sympy.Matrix.row_del() Method Read More »

Python Numpy matrix.min() Function

NumPy Library 

NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it into our program and then we can easily use the functionality of NumPy in our program.

NumPy is a Python library that is frequently used for scientific and statistical analysis. NumPy arrays are grids of the same datatype’s values.

Numpy matrix.min() Function:

We can obtain the minimum value from a given matrix using the matrix.min() method of the Numpy module.

Syntax:

 matrix.min()

Return Value:

The minimum value from a given matrix is returned by the min() function.

Numpy matrix.min() Function in Python

For 2-Dimensional (2D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing some random 2D matrix as an argument to it and store it in a variable
  • Apply the min() function on the given matrix to get the minimum value from a given matrix.
  • Store it in another variable
  • Print the minimum value from a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing 
# some random 2D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[1, 15; 4, 5]')
            
# Apply the min() function on the given matrix to get the minimum value from a given matrix.
# Store it in another variable
rslt = gvn_matrx.min()
# Print the minimum value from a given matrix.
print("The minimum value from a given matrix is:")
print(rslt)

Output:

The minimum value from a given matrix is:
1

For 3-Dimensional (3D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing some random 3D matrix as an argument to it and store it in a variable
  • Apply the min() function on the given matrix to get the minimum value from a given matrix.
  • Store it in another variable
  • Print the minimum value from a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing 
# some random 3D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[10, 3, 5; 4, 30, 12; 50, 7, 9]')
            
# Apply the min() function on the given matrix to get the minimum value from a given matrix.
# Store it in another variable
rslt = gvn_matrx.min()
# Print the minimum value from a given matrix.
print("The minimum value from a given matrix is:")
print(rslt)

Output:

The minimum value from a given matrix is:
3

Python Numpy matrix.min() Function Read More »

Python Numpy matrix.max() Function

NumPy Library 

NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it into our program and then we can easily use the functionality of NumPy in our program.

NumPy is a Python library that is frequently used for scientific and statistical analysis. NumPy arrays are grids of the same datatype’s values.

Numpy matrix.max() Function:

We can obtain the maximum value from a given matrix using the matrix.max() method of the Numpy module.

Syntax:

 matrix.max()

Return Value:

The maximum value from a given matrix is returned by the max() function.

Numpy matrix.max() Function in Python

For 2-Dimensional (2D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing some random 2D matrix as an argument to it and store it in a variable
  • Apply the max() function on the given matrix to get the maximum value from a given matrix.
  • Store it in another variable
  • Print the maximum value from a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing 
# some random 2D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[1, 15; 4, 5]')
            
# Apply the max() function on the given matrix to get the maximum value from a given matrix.
# Store it in another variable
rslt = gvn_matrx.max()
# Print the maximum value from a given matrix.
print("The maximum value from a given matrix is:")
print(rslt)

Output:

The maximum value from a given matrix is:
15

For 3-Dimensional (3D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing some random 3D matrix as an argument to it and store it in a variable
  • Apply the max() function on the given matrix to get the maximum value from a given matrix.
  • Store it in another variable
  • Print the maximum value from a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing 
# some random 3D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[10, 2, 5; 1, 30, 12; 50, 7, 9]')
            
# Apply the max() function on the given matrix to get the maximum value from a given matrix.
# Store it in another variable
rslt = gvn_matrx.max()
# Print the maximum value from a given matrix.
print("The maximum value from a given matrix is:")
print(rslt)

Output:

The maximum value from a given matrix is:
50

Python Numpy matrix.max() Function Read More »

Python Scipy stats.hypsecant.cdf() Function

Scipy Library in Python:

  • SciPy is a scientific computation package that uses the NumPy library underneath.
  • SciPy is an abbreviation for Scientific Python.
  • It includes additional utility functions for optimization, statistics, and signal processing.
  • SciPy, like NumPy, is open source, so we can freely use it.
  • Travis Olliphant, the developer of NumPy, created SciPy.
  • SciPy has optimized and added/enhanced functions that are often used in NumPy and Data Science.

Scipy stats.halfgennorm.cdf() Function:

We can obtain the value of the cumulative distribution function by using the stats.hypsecant.cdf() method.

Syntax:

stats.hypsecant.cdf(x, beta)

Return Value:

The cumulative distribution value is returned by the cdf() function.

Scipy stats.hypsecant.cdf() Function in Python

Method #1: Using cdf() Function (Static Input)

Approach:

  • Import hypsecant from stats of scipy module using the import keyword
  • Give the beta value as static input and store it in a variable.
  • Pass some random value(x), beta value as arguments cdf() function of hypsecant to the get the value of the cumulative distribution function and store it in another variable.
  • Print the cumulative distribution function value for the given beta value.
  • The Exit of the Program.

Below is the implementation:

# Import hypsecant from stats of scipy module using the import keyword
from scipy.stats import hypsecant
# Give the beta value as static input and store it in a variable.
gvn_beta = 3

# Pass some random value(x), beta value as arguments cdf() function of hypsecant
# to the get the value of the cumulative distribution function and store it in another variable.
rslt = hypsecant.cdf(0.2, gvn_beta)
# Print the cumulative distribution function value for the given beta value
print("The cumulative distribution function value for the given beta value is:")
print(rslt)

Output:

The cumulative distribution function value for the given beta value is:
0.03866527549256035

Method #2: Using cdf() Function (User Input)

Approach:

  • Import hypsecant from stats of scipy module using the import keyword
  • Give the beta value as static input and store it in a variable.
  • Pass some random value(x), beta value as arguments cdf() function of hypsecant to the get the value of the cumulative distribution function and store it in another variable.
  • Print the cumulative distribution function value for the given beta value.
  • The Exit of the Program.

Below is the implementation:

# Import hypsecant from stats of scipy module using the import keyword
from scipy.stats import hypsecant
# Give the beta value as user input using the int(input()) function and store it in a variable.
gvn_beta = int(input("Enter some random number = "))

# Pass some random value(x), beta value as arguments cdf() function of hypsecant
# to the get the value of the cumulative distribution function and store it in another variable.
rslt = hypsecant.cdf(0.6, gvn_beta)
# Print the cumulative distribution function value for the given beta value
print("The cumulative distribution function value for the given beta value{",gvn_beta,"} is:")
print(rslt)

Output:

Enter some random number = 2
The cumulative distribution function value for the given beta value{ 2 } is:
0.1539176313854603

Python Scipy stats.hypsecant.cdf() Function Read More »

Python Scipy stats.halfgennorm.stats() Function

Scipy Library in Python:

  • SciPy is a scientific computation package that uses the NumPy library underneath.
  • SciPy is an abbreviation for Scientific Python.
  • It includes additional utility functions for optimization, statistics, and signal processing.
  • SciPy, like NumPy, is open source, so we can freely use it.
  • Travis Olliphant, the developer of NumPy, created SciPy.
  • SciPy has optimized and added/enhanced functions that are often used in NumPy and Data Science.

Scipy stats.halfgennorm.stats() Function

We can obtain the value of Mean(‘m’), variance(‘v’), skew (‘s’), and/or kurtosis(‘k’) by using the stats.halfgennorm.stats() function.

Syntax:

 stats.halfgennorm.stats(beta, moments)

Return Value:

The value of mean, variance, skew, and kurtosis is returned by the stats() function.

Scipy stats.halfgennorm.stats() Function in Python

Method #1: Using stats() Function (Static Input)

Approach:

  • Import halfgennorm() method from stats of scipy module using the import keyword
  • Give the beta value as static input and store it in a variable.
  • Pass the given beta value, moments =’mvsk’ as arguments to the stats() function of halfgennorm module to get the values of Mean, Variance, Skew, kurtosis for the given beta value.
  • Store them in 4 separate variables
  • Print the values of Mean, Variance, Skew, kurtosis for the given beta value.
  • The Exit of the Program.

Below is the implementation:

# Import halfgennorm() method from stats of scipy module using the import keyword
from scipy.stats import halfgennorm
# Give the beta value as static input and store it in a variable.
gvn_beta = 3

# Pass the given beta value, moments ='mvsk' as arguments to the stats() function of 
# halfgennorm module to get the values of Mean, Variance, Skew, kurtosis for the given beta value.
# Store them in 4 separate variables 
Mean, Variance, Skew, kurtosis = halfgennorm.stats(gvn_beta, moments ='mvsk')
# Print the values of Mean, Variance, Skew, kurtosis for the given beta value
print("The values of Mean, Variance, Skew, kurtosis for the given beta{",gvn_beta,"} value:")
print(Mean, Variance, Skew, kurtosis)

Output:

The values of Mean, Variance, Skew, kurtosis for the given beta{ 3 } value:
0.5054680881515111 0.1177841857623046 0.6327758514663764 -0.15848408785769097

Method #2: Using stats() Function (User Input)

Approach:

  • Import halfgennorm() method from stats of scipy module using the import keyword
  • Give the beta value as user input using the int(input()) function and store it in a variable.
  • Pass the given beta value, moments =’mvsk’ as arguments to the stats() function of halfgennorm module to get the values of Mean, Variance, Skew, kurtosis for the given beta value.
  • Store them in 4 separate variables
  • Print the values of Mean, Variance, Skew, and kurtosis for the given beta value.
  • The Exit of the Program.

Below is the implementation:

# Import halfgennorm() method from stats of scipy module using the import keyword
from scipy.stats import halfgennorm

# Give the beta value as user input using the int(input()) function and store it in a variable.
gvn_beta = int(input("Enter some random number = "))

# Pass the given beta value, moments ='mvsk' as arguments to the stats() function of 
# halfgennorm module to get the values of Mean, Variance, Skew, kurtosis for the given beta value.
# Store them in 4 separate variables 
Mean, Variance, Skew, kurtosis = halfgennorm.stats(gvn_beta, moments ='mvsk')
# Print the values of Mean, Variance, Skew, kurtosis for the given beta value
print("The values of Mean, Variance, Skew, kurtosis for the given beta{",gvn_beta,"} value:")
print(Mean, Variance, Skew, kurtosis)

Output:

Enter some random number = 2
The values of Mean, Variance, Skew, kurtosis for the given beta{ 2 } value:
0.5641895835415295 0.1816901138291821 0.9952717461750911 0.8691773035274091

Python Scipy stats.halfgennorm.stats() Function Read More »

Python Program to Search for an Element in the Linked List using Recursion

Linked List Data Structure:

A linked list is a type of data structure that consists of a chain of nodes, each of which contains a value and a pointer to the next node in the chain.

The list’s head pointer points to the first node, and the list’s last element points to null. The head pointer points to null when the list is empty.

Linked lists can grow in size dynamically, and inserting and deleting elements from them is simple because, unlike arrays, we only need to change the pointers to the previous and next elements to insert or delete an element.

Linked lists are commonly used in the construction of file systems, adjacency lists, and hash tables.

Given an Element and LinkedList, the Task is to check whether the given element is present in the LinkedList or not in Python.

Examples:

Example1:

Input:

Given LinkedList : 5 1 7 8 9 11 13
Given Element : 9

Output:

True

Example2:

Input:

Given LinkedList : 1 9 3 5
Given Element : 2

Output:

False

Program to Search for an Element in the Linked List using Recursion in Python

Approach:

  • Create a class that creates a node of the LinkedList.
  • Create a constructor that accepts val as an argument and initializes the class variable val with the given argument val.
  • Initializing the next Pointer(Last Node Pointer to None i.e Null).
  • Create a Class Which Creates the LinkedList by connecting all the nodes.
  • Inside the class, the constructor Initialize the head pointer to None(Null) and the last Node pointer to Null.
  • Create a function addElements() inside the class which accepts the data value as an argument and add this node to the LinkedList.
  • Check if the lastNode Pointer is None using the if conditional statement.
  • If the above if condition is true(If there are no elements in the linked list) then Create a Node using the Node class by passing the data as an argument.
  • Initialize the head with the above node.
  • Else Create the new node and initialize the last node pointer Value to the new node.
  • Set the last node Pointer Value to the Next Pointer.
  • Create a Recursive function SearchElement() inside the class which accepts the element and Linkedlist Object as arguments and searches whether the given element is present in the LinkedList or not
  • Base case(Check if the lkdList is null or not using the if conditional statement)
  • If it is true then return False(Element not found as there are no elements in the LinkedList)
  • Check if the given element is equal to node of the LinkedList using the If condtional statement
  • If it is true then return True(Element is present)
  • Else increment the Linkedlist Pointer to the next node using the recursion
  • Take an object for the LinkedList Class and store it in a variable.
  • Add elements to the LinkedList by using the below steps.
  • Loop till the above number of elements using the For loop.
  • Give the data value as user input and store it in a variable.
  • Pass the above value as an argument to the addElements() function to add this value as a node to the LinkedList.
  • Give the element to search as user input and store it in a variable
  • Printing whether the element is present or not in the LinkedList by calling the SearchElement() of the above object.
  • The Exit of the Program.

Below is the implementation:

# Create a class that creates a node of the LinkedList.
class Node:
    # Create a constructor that accepts val as an argument and initializes the class variable val with the given argument val.
    def __init__(self, val):
        self.val = val
        # Initializing the next Pointer(Last Node Pointer to None i.e Null).
        self.nextPtr = None
  # Create a Class Which Creates the LinkedList by connecting all the nodes.


class LinkedList:
  # Inside the class, the constructor Initialize the head pointer to None(Null) and the last Node pointer to Null.
    def __init__(self):
        self.headPtr = None
        self.lastNode = None
    # Create a function addElements() inside the class which accepts the data value as an argument and add this node to the LinkedList.

    def addElements(self, val):
        # Check if the lastNode Pointer is None using the if conditional statement.
        if self.lastNode is None:
          # If the above if condition is true(If there are no elements in the linked list)
          # then Create a Node using the Node class by passing the data as an argument.
          # Initialize the head with the above node.
            self.headPtr = Node(val)
            self.lastNode = self.headPtr
        else:
          # Else Create the new node and initialize the last node pointer Value to the new node.
            self.lastNode.nextPtr = Node(val)
            # Set the last node Pointer Value to the Next Pointer.
            self.lastNode = self.lastNode.nextPtr
    # Create a Recursive function SearchElement() inside the class which accepts the element and Linkedlist Object as arguments
    # and searches whether the given element is present in the LinkedList or not

    def SearchElement(self, lkdList, elem):
      # Base case(Check if the lkdList is null or not using the if conditional statement)
        if(not lkdList):
          # If it is true then return False(Element not found as there are no elements in the LinkedList)
            return False
        # Check if the given element is equal to node of the LinkedList using the If condtional statement
        if(lkdList.val == elem):
          # If it is true then return True(Element is present)
            return True
        # Else increment the Linkedlist Pointer to the next node using the recursion
        return self.SearchElement(lkdList.nextPtr, elem)


# Take an object for the LinkedList Class and store it in a variable.
lkdList = LinkedList()
# Add elements to the LinkedList by using the below steps.
n = int(input('Enter the number of elements you wish to add in the linked list = '))
# Loop till the above number of elements using the For loop.
for i in range(n):
    # Give the data value as user input and store it in a variable.
    val = int(input('Enter data item: '))
    # Pass the above value as an argument to the addElements() function to add this value as a node to the LinkedList.
    lkdList.addElements(val)
# Give the element to search as user input and store it in a variable
elem = int(input('Enter the element to search in the LinkedList : '))
# Printing whether the element is present or not in the LinkedList by calling the SearchElement() of the above object.
print(lkdList.SearchElement(lkdList.headPtr, elem))

Output:

Enter the number of elements you wish to add in the linked list = 8
Enter data item: 11
Enter data item: 3
Enter data item: 2
Enter data item: 8
Enter data item: 6
Enter data item: 9
Enter data item: 15
Enter data item: 43
Enter the element to search in the LinkedList : 15
True

Python Program to Search for an Element in the Linked List using Recursion Read More »

Python Program to Display the Nodes of a Linked List in Reverse using Recursion

Linked List Data Structure:

A linked list is a type of data structure that consists of a chain of nodes, each of which contains a value and a pointer to the next node in the chain.

The list’s head pointer points to the first node, and the list’s last element points to null. The head pointer points to null when the list is empty.

Linked lists can grow in size dynamically, and inserting and deleting elements from them is simple because, unlike arrays, we only need to change the pointers to the previous and next elements to insert or delete an element.

Linked lists are commonly used in the construction of file systems, adjacency lists, and hash tables.

Given a LinkedList, the task is to print all the elements of the LinkedList in Reverse order using recursion in Python.

Examples:

Example1:

Input:

Given LinkedList : 56 45 23 14 9 8 2 5 4 3 12

Output:

The Elements of the LinkedList in Reverse Order are :
12 3 4 5 2 8 9 14 23 45 56

Example2:

Input:

Given LinkedList : 1 9 3

Output:

The Elements of the LinkedList in Reverse Order are :
3 9 1

Program to Display the Nodes of a Linked List in Reverse using Recursion in Python

Approach:

  • Create a class that creates a node of the LinkedList.
  • Create a constructor that accepts val as an argument and initializes the class variable val with the given argument val.
  • Initializing the next Pointer(Last Node Pointer to None i.e Null).
  • Create a Class Which Creates the LinkedList by connecting all the nodes.
  • Inside the class, the constructor Initialize the head pointer to None(Null) and the last Node pointer to Null.
  • Create a function addElements() inside the class which accepts the data value as an argument and add this node to the LinkedList.
  • Check if the lastNode Pointer is None using the if conditional statement.
  • If the above if condition is true(If there are no elements in the linked list) then Create a Node using the Node class by passing the data as an argument.
  • Initialize the head with the above node.
  • Else Create the new node and initialize the last node pointer Value to the new node.
  • Set the last node Pointer Value to the Next Pointer.
  • Create a Recursive function printRecursive() inside the class which accepts the temp pointer(Here value of temp pointer at first points to headptr node) of the linkedList and prints all the nodes values of the LinkedList.
  • Check if the tempPtr is null or not using the If condtional Statement(If it is null then there are no elements in the LinkedList).
  • If there are elements in the LinkedList then the value of tempPtr is not null.
  • If the tempPtr is not null then call the recursive function by pointing the next node of the tempPtr.
  • Print the value at the tempPtr node.
  • Else return.
  • Take an object for the LinkedList Class and store it in a variable.
  • Add elements to the LinkedList by using the below steps.
  • Loop till the above number of elements using the For loop.
  • Give the data value as user input and store it in a variable.
  • Pass the above value as an argument to the addElements() function to add this value as a node to the LinkedList.
  • Printing all elements of the LinkedList by passing the headPtr as an argument to the printRecursive() function.
  • The Exit of the Program.

Below is the Implementation:

# Create a class that creates a node of the LinkedList.
class Node:
    # Create a constructor that accepts val as an argument and initializes the class variable val with the given argument val.
    def __init__(self, val):
        self.val = val
        # Initializing the next Pointer(Last Node Pointer to None i.e Null).
        self.nextPtr = None
  # Create a Class Which Creates the LinkedList by connecting all the nodes.


class LinkedList:
  # Inside the class, the constructor Initialize the head pointer to None(Null) and the last Node pointer to Null.
    def __init__(self):
        self.headPtr = None
        self.lastNode = None
    # Create a function addElements() inside the class which accepts the data value as an argument and add this node to the LinkedList.

    def addElements(self, val):
        # Check if the lastNode Pointer is None using the if conditional statement.
        if self.lastNode is None:
          # If the above if condition is true(If there are no elements in the linked list)
          # then Create a Node using the Node class by passing the data as an argument.
          # Initialize the head with the above node.
            self.headPtr = Node(val)
            self.lastNode = self.headPtr
        else:
          # Else Create the new node and initialize the last node pointer Value to the new node.
            self.lastNode.nextPtr = Node(val)
            # Set the last node Pointer Value to the Next Pointer.
            self.lastNode = self.lastNode.nextPtr
    # Create a Recursive function printRecursive() inside the class which accepts the temp pointer(Here value of temp pointer at first points to headptr node)
    # of the linkedList and prints all the nodes values of the LinkedList

    def printRecursive(self, tempPtr):
        # Check if the tempPtr is null or not using the If condtional Statement(If it is null then there are no elements in the LinkedList)
        # If there are elements in the LinkedList then the value of tempPtr is not null
        if tempPtr:
            # If the tempPtr is not null then call the recursive function by pointing the next node of the tempPtr
            self.printRecursive(tempPtr.nextPtr)
            # Print the value at the tempPtr node
            print(tempPtr.val, end=' ')
        # Else return
        else:
            return


# Take an object for the LinkedList Class and store it in a variable.
lkdList = LinkedList()
# Add elements to the LinkedList by using the below steps.
n = int(input('Enter the number of elements you wish to add in the linked list = '))
# Loop till the above number of elements using the For loop.
for i in range(n):
    # Give the data value as user input and store it in a variable.
    val = int(input('Enter data item: '))
    # Pass the above value as an argument to the addElements() function to add this value as a node to the LinkedList.
    lkdList.addElements(val)
# Printing all elements of the LinkedList by passing the headPtr as argument to the printRecursive() function
print('The Elements of the LinkedList in Reverse Order are :')
lkdList.printRecursive(lkdList.headPtr)

Output:

Enter the number of elements you wish to add in the linked list = 11
Enter data item: 12
Enter data item: 3
Enter data item: 4
Enter data item: 5
Enter data item: 2
Enter data item: 8
Enter data item: 9
Enter data item: 14
Enter data item: 23
Enter data item: 45
Enter data item: 56
The Elements of the LinkedList in Reverse Order are :
56 45 23 14 9 8 2 5 4 3 12

 

Python Program to Display the Nodes of a Linked List in Reverse using Recursion Read More »

Python Program to Search for an Element in the Linked List without using Recursion

Linked List Data Structure:

A linked list is a type of data structure that consists of a chain of nodes, each of which contains a value and a pointer to the next node in the chain.

The list’s head pointer points to the first node, and the list’s last element points to null. The head pointer points to null when the list is empty.

Linked lists can grow in size dynamically, and inserting and deleting elements from them is simple because, unlike arrays, we only need to change the pointers to the previous and next elements to insert or delete an element.

Linked lists are commonly used in the construction of file systems, adjacency lists, and hash tables.

Given an Element and LinkedList, the Task is to check whether the given element is present in the LinkedList or not in Python.

Examples:

Example1:

Input:

Given LinkedList : 5 1 7 8 9 11 13
Given Element : 9

Output:

True

Example2:

Input:

Given LinkedList : 1 9 3 5
Given Element : 2

Output:

False

Program to Search for an Element in the Linked List without using Recursion in Python

Approach:

  • Create a class that creates a node of the LinkedList.
  • Create a constructor that accepts val as an argument and initializes the class variable val with the given argument val.
  • Initializing the next Pointer(Last Node Pointer to None i.e Null).
  • Create a Class Which Creates the LinkedList by connecting all the nodes.
  • Inside the class, the constructor Initialize the head pointer to None(Null) and the last Node pointer to Null.
  • Create a function addElements() inside the class which accepts the data value as an argument and add this node to the LinkedList.
  • Check if the lastNode Pointer is None using the if conditional statement.
  • If the above if condition is true(If there are no elements in the linked list) then Create a Node using the Node class by passing the data as an argument.
  • Initialize the head with the above node.
  • Else Create the new node and initialize the last node pointer Value to the new node.
  • Set the last node Pointer Value to the Next Pointer.
  • Create a function SearchElement() inside the class which accepts the element as argument and searches whether the given element is present in the LinkedList or not
  • Take a Pointer that points to the nodes of the LinkedList and initialize its value to the Head Pointer.
  • Loop till the temPtr is None(null) using the while loop.
  • Check if the value of the node is equal to the given element using the if conditional statement
  • If it is true then return True
  • Else Increment the temPtr to the Next Node.
  • Return False(Element is not Found)
  • Take an object for the LinkedList Class and store it in a variable.
  • Add elements to the LinkedList by using the below steps.
  • Loop till the above number of elements using the For loop.
  • Give the data value as user input and store it in a variable.
  • Pass the above value as an argument to the addElements() function to add this value as a node to the LinkedList.
  • Give the element to search as user input and store it in a variable
  • Printing whether the element is present or not in the LinkedList by calling the SearchElement() of the above object.
  • The Exit of the Program.

Below is the implementation:

# Create a class that creates a node of the LinkedList.
class Node:
    # Create a constructor that accepts val as an argument and initializes the class variable val with the given argument val.
    def __init__(self, val):
        self.val = val
        # Initializing the next Pointer(Last Node Pointer to None i.e Null).
        self.nextPtr = None
  # Create a Class Which Creates the LinkedList by connecting all the nodes.


class LinkedList:
  # Inside the class, the constructor Initialize the head pointer to None(Null) and the last Node pointer to Null.
    def __init__(self):
        self.headPtr = None
        self.lastNode = None
    # Create a function addElements() inside the class which accepts the data value as an argument and add this node to the LinkedList.

    def addElements(self, val):
        # Check if the lastNode Pointer is None using the if conditional statement.
        if self.lastNode is None:
          # If the above if condition is true(If there are no elements in the linked list)
          # then Create a Node using the Node class by passing the data as an argument.
          # Initialize the head with the above node.
            self.headPtr = Node(val)
            self.lastNode = self.headPtr
        else:
          # Else Create the new node and initialize the last node pointer Value to the new node.
            self.lastNode.nextPtr = Node(val)
            # Set the last node Pointer Value to the Next Pointer.
            self.lastNode = self.lastNode.nextPtr
    # Create a function SearchElement() inside the class which accepts the element as argument
    # and searches whether the given element is present in the LinkedList or not

    def SearchElement(self, elem):
      # Take a Pointer that points to the nodes of the LinkedList and initialize its value to the Head Pointer.
        temPtr = self.headPtr
        # Loop till the temPtr is None(null) using the while loop.
        while temPtr is not None:
            # Check if the value of the node is equal to the given element using the if conditional statement
            if(temPtr.val == elem):
                # If it is true then return True
                return True
            # Else Increment the temPtr to the Next Node.
            temPtr = temPtr.nextPtr
        #Return False(Element is not Found)
        return False
# Take an object for the LinkedList Class and store it in a variable.
lkdList = LinkedList()
# Add elements to the LinkedList by using the below steps.
n = int(input('Enter the number of elements you wish to add in the linked list = '))
# Loop till the above number of elements using the For loop.
for i in range(n):
    # Give the data value as user input and store it in a variable.
    val = int(input('Enter data item: '))
    # Pass the above value as an argument to the addElements() function to add this value as a node to the LinkedList.
    lkdList.addElements(val)
#Give the element to search as user input and store it in a variable
elem=int(input('Enter the element to search in the LinkedList : '))    
# Printing whether the element is present or not in the LinkedList by calling the SearchElement() of the above object.
print(lkdList.SearchElement(elem))

Output:

Enter the number of elements you wish to add in the linked list = 7
Enter data item: 2
Enter data item: 11
Enter data item: 5
Enter data item: 9
Enter data item: 7
Enter data item: 17
Enter data item: 14
Enter the element to search in the LinkedList : 7
True

Python Program to Search for an Element in the Linked List without using Recursion Read More »