Author name: Vikram Chiluka

Difference Between List and Tuple in Python

In this tutorial, let us look at the key differences between the list and tuple in python with examples.

List and tuple are data structures in Python that can store one or more objects or values. A list, which can be created with square brackets, is used to store multiple items in one variable. Similarly, tuples, which can be declared with parentheses, can store multiple items in a single variable.
The list has dynamic properties, whereas the tuple has static properties.

List

List objects are declared similarly to arrays in other programming languages. Lists do not have to be homogeneous all of the time, so they can store items of different data types at the same time. As a result, lists are the most useful tool. The list is a Python container data Structure that is used to hold multiple pieces of data at the same time. Lists come in handy when we need to iterate over some elements while keeping hold of the items.

Tuple

A Tuple is a sequence data type that can contain elements of various data types, but it is immutable. A tuple is simply a collection of Python objects separated by commas. Because tuples are static in nature, they are faster than lists.

Let us now look at the major differences between the list and tuple along with the examples.

Difference Between List and Tuple in Python

1)Syntax Differences

The syntax of the list and tuple differs slightly. Lists are denoted by square brackets [], while Tuples are denoted by parenthesis ().

# Give the list as static input and store it in a variable
gvn_lst = [5, 8, 1, 2]
# Give the tuple as static input and store it in a variable
gvn_tuple = (5, 8, 1, 2)

# print the given list
print("The given list = ", gvn_lst)
# print the given tuple
print("The given tuple = ", gvn_tuple)

# print the datatype of given list using the type() function
print("The datatype of given list = ", type(gvn_lst))
# print the datatype of given list using the type() function
print("The datatype of given list = ", type(gvn_tuple))

Output:

The given list = [5, 8, 1, 2]
The given tuple = (5, 8, 1, 2)
The datatype of given list = <class 'list'>
The datatype of given list = <class 'tuple'>

2)List is Mutable where as Tuple is Immutable

A key difference between a list and a tuple is that lists are mutable whereas tuples are immutable. What does this mean exactly? It means that the items in a list can be changed or modified, whereas the items in a tuple cannot be changed or modified.

Because a list is mutable, we cannot use it as a dictionary key. This is due to the fact that a Python dictionary key is an immutable object. As a result, tuples can be used as dictionary keys if necessary.

# Give the list as static input and store it in a variable
gvn_lst = [5, 8, 1, 2]
# Give the tuple as static input and store it in a variable
gvn_tuple = (5, 8, 1, 2)

# Modifying the list element at the index 1
gvn_lst[1] = 10
# print the given list after modification
print("The given list after modification = ", gvn_lst)

# Modifying the tuple element at the index 1
# Here we get an error because as the tuple is immutable, the elements of a tuple cannot be changed
gvn_tuple[1] = 10
print(gvn_tuple)

Output:

The given list after modification = [5, 10, 1, 2]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-306436f9dc4b> in <module>
11 # Modifying the tuple element at the index 1
12 # Here we get an error because as the tuple is immutable, the elements of a tuple cannot be changed
---> 13 gvn_tuple[1] = 10
14 print(gvn_tuple)

TypeError: 'tuple' object does not support item assignment

Explanation:

Here, we assigned 10 to gvn_lst at index 1 and found 10 at index 1
in the output. 
We also got a type error when we assigned 10 to gvn_tuple at index 1. 
We can't change the tuple because it's immutable.

3)Comparison in Size

Tuples operations have a smaller size than list operations, which makes them a little faster, but not by much unless you have a large number of elements.

# Give the list as static input and store it in a variable
gvn_lst = [5, 8, 1, 2, 7, 8, 10, 15, 18, 20]
# Give the tuple as static input and store it in a variable
gvn_tuple = (5, 8, 1, 2, 7, 8, 10, 15, 18, 20)

print('Given list size =', gvn_lst.__sizeof__())
print('Given tuple size =', gvn_tuple.__sizeof__())

Output:

Given list size = 120
Given tuple size = 104

4)Available Functions

Lists have more built-in functions than tuples. We can use the built-in function dir([object] to access all of the list and tuple’s methods.

The number of methods available in these two also differs, with tuples having 33 methods and lists having 46.

# Give the list as static input and store it in a variable
gvn_lst = [5, 8, 1, 2]
# Give the tuple as static input and store it in a variable
gvn_tuple = (5, 8, 1, 2)

print(dir(gvn_lst))
print(dir(gvn_tuple))

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

List vs Tuple

                        List                         Tuple
MutableImmutable
In the list, the implication of iterations is time-consuming.Iteration implications are much faster in tuples.
The list performs better for operations like insertion and deletion.Elements can be accessed better in tuples
The Lists consume more memoryWhen compared to a list, a tuple consumes less memory.
Have More built-in functionsTuples have fewer built-in functions when compared to lists
In lists, Unexpected changes and errors are more likely to occur.Tuples rarely generate unexpected errors or changes.

List vs Tuple Similarities

  • Both lists and tuples hold collections of elements and are heterogeneous data types, which means they can hold multiple data types at the same time.
  • They are both ordered, which means the items or objects will remain in the same order in which they were placed until manually changed.
  • We can iterate through the objects they hold because they are both sequential data structures; thus, they are iterable.
  • A square bracketed [index] integer index can be used to access objects of both data types.

Difference Between List and Tuple in Python Read More »

Encapsulation in Python

Encapsulation, along with abstraction, inheritance, and polymorphism, is a fundamental concept in object-oriented programming (OOP).

In this post, let us look at what is encapsulation with the examples to understand it more clearly.

Encapsulation

Encapsulation is the process of wrapping up variables and methods into a single entity. It is a fundamental idea in object-oriented programming (OOP). It works as a protective shield, limiting direct access to variables and methods and preventing accidental or unauthorized data alteration. Encapsulation also turns objects into more self-sufficient, self-contained (independently functioning)units.

Real-time Example

Consider the following real-world example of encapsulation. A company has various sections, such as the accounts and finance sections. The finance department controls all financial transactions and data. The sales department is also in charge of all sales-related activities. They keep track of every sale. A finance officer may require full sales data for a certain month at times. He is not permitted to see the data from the sales area in this case. He must first call another officer in the sales unit to request the data. This is called encapsulation.

Access Modifiers in Encapsulation

While programming, it may be necessary to restrict or limit access to particular variables or functions. This is where access modifiers come into play.

When it comes to access, there are three types of access specifiers that can be utilised while executing Encapsulation in Python. They are:

  • Public Members
  • Private Members
  • Protected Members

Public Members

Members of the public can be accessed from anywhere from a class. By default, all of the class variables are public.

Approach:

  • Create a class say employDetails
  • Create a __init_ constructor which accepts employName and employId as arguments
  • Create public data members inside the class.
  • Create a function say displayEmployId which prints the employ id when it is called
  • Access the public data member of the class and print the result
  • Create an object of the class employDetails
  • Access the public data member of the class and print the result
  • Call the public member function displayEmployId of the class employDetails.
  • The Exit of the Program.

Below is the implementation:

# create a class say employDetails
class employDetails:

    # Create a __init_ constructor which accepts employName and employId as arguments 
    def __init__(self, employName, employId):
        # create public data members
        self.employName = employName;
        self.employId = employId;

    # Create a function say displayEmployId which prints 
    # the employ id when it is called
    def displayEmployId(self): 
        # Access the public data member of the class and print the result
        print("employId: ", self.employId)

# create an object of the class employDetails
employdetails_obj = employDetails("John", 2122);

# Access the public data member of the class and print the result
print("employName: ", employdetails_obj.employName)  

# call the public member function displayEmployId of the class employDetails
employdetails_obj.displayEmployId()

Output:

employName: John
employId: 2122

The variable employName and employId are both public in class employDetails. These data members are available throughout the program.

Private Members

Private members are accessible within the class. To define a private member, use a double underscore “__” before the member name.

Private members and protected members are the same thing. The difference is that private class members should not be accessed by anyone outside the class or its base classes. Private instance variable variables that can be accessed outside of a class do not exist in Python.

Python’s private and secured members can be accessed from outside the class by renaming them.

Approach:

  • Create a class say employDetails
  • Create a __init_ constructor which accepts employName and employId as arguments
  • Create a public variable inside the class
  • Create private variable prefixed with “__” inside the class
  • Create an object of the class employDetails and call it.
  • Access the public variable name of the class and print the result.
  • Access the private data variable __employId of the class employDetails and print the result.
  • The Exit of the Program.

Below is the implementation:

# create a class say employDetails
class employDetails:
   
   # Create a __init_ constructor which accepts employName and employId as arguments 
   def __init__(self, employName, employId):
      # Create a public variable
      self.employName = employName
      # Create private variable prefixed with "__"
      self.__employId = employId

# create an object of the class employDetails and call it
employdetails_obj = employDetails("John", 2122)

# Access the public variable name of the class and print the result
print("employName:",employdetails_obj.employName)

# Access the private data variable __employId of the class employDetails and print the result
print("employId:",employdetails_obj._employDetails__employId)

Output:

employName: John
employId: 2122

__employId is a private variable in class employDetails; thus, it is accessed by creating an object/instance.

Protected Members

Protected members can be accessed both within the class and by its subclasses. To define a protected member, use a single underscore “_” before the member name.

The protected variable can be accessed from the class and in derived classes (it can even be updated in derived classes), but it is not usually accessed outside of the class body.

The __init__ method(constructor), runs when an object of a type is instantiated.

# create a class say employDetails
class employDetails:
    # Creat which accepts employName and employId as arguments  
    def __init__(self, employName, employId):
        # protected data members as they are prefixed with single underscore "_"
        self._employName = employName
        self._employId = employId

# create object of the class employDetails and call it 
employdetails_obj = employDetails("John", 2122)

# Access the protected members of the class and print the result
print("employName:",employdetails_obj._employName)
print("employId:",employdetails_obj._employId)

Output:

employName: John
employId: 2122

Advantages of Encapsulation

1)Encapsulation ensures that code is well-defined and readable.

The fundamental benefit of using Encapsulation in Python is that as users, we do not need to understand the architecture of the functions and data and can instead focus on using these functional, encapsulated units in our applications. As a result, the code is more organized and clean. The user experience also improves significantly, making it easier to comprehend apps as a whole.

2)Encapsulation Prevents Accidental Modification/Deletion

Another advantage of encapsulation is that it protects data and methods from being accidentally modified. Consider the NumPy example again: if I had access to the library, I might introduce a mistake in the implementation of the mean function, and as a result, millions of NumPy projects would become incorrect.

3)Encapsulation ensures security

Python encapsulation is achieved with access modifiers. These access modifiers ensure that access conditions are not violated, resulting in a positive user experience in terms of security.

 

Encapsulation in Python Read More »

Python Numpy matrix.ptp() 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.ptp() Function:

Using the matrix.ptp() method of the Numpy module, we can obtain the peek-to-peek value i.e, is (maximum-minimum) along the axis from a specified matrix.

Syntax:

 matrix.ptp(axis)

Return Value:

The peek-to-peek value from a given matrix is returned by the ptp() function.

Numpy matrix.ptp() 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 arguments to it and store it in a variable
  • Print the given matrix
  • Pass random axis(0/1) as an argument to the ptp() function and apply it to the given matrix to get the peek-to-peek(maximum-minimum) value along the specified axis from a given matrix.
  • Here 0 represents along the column, and 1 represents a row.
  • Store it in another variable
  • Print the peek-to-peek value along the specified axis 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 arguments to it and store it in a variable
gvn_matrx = np.matrix('[10, 1; 6, 3]')
# Print the given matrix
print("The given matrix is:\n", gvn_matrx)    

# Pass random axis(0/1) as an argument to the ptp() function and apply it to the given matrix
# to get the peek-to-peek(maximum-minimum) value along the specified axis from a given matrix.
# Here 0 represents along column, 1 represents row.
# Store it in another variable
rslt = gvn_matrx.ptp(1)
# Print the peek-to-peek value along the specified axis from a given matrix.
print("The peek-to-peek value along the specified axis from a given matrix:")
print(rslt)

Output:

The given matrix is:
[[10 1]
 [ 6 3]]
The peek-to-peek value along the specified axis from a given matrix:
[[9]
 [3]]

Explanation:

Here it prints 10-1 = 9,  6-3=3 i.e, along the row

NOTE:

Here 0 represents along the column, and 1 represents a row.
but generally 0 = row, 1=column.

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 arguments to it and store it in a variable
  • Print the given matrix
  • Pass random axis(0/1) as an argument to the ptp() function and apply it to the given matrix to get the peek-to-peek(maximum-minimum) value along the specified axis from a given matrix.
  • Here 0 represents along the column, and 1 represents a row.
  • Store it in another variable
  • Print the peek-to-peek value along the specified axis 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('[2, 4, 1; 8, 7, 3; 10, 9, 5]')
# Print the given matrix
print("The given matrix is:\n", gvn_matrx)    

# Pass random axis(0/1) as an argument to the ptp() function and apply it to the given matrix
# to get the peek-to-peek(maximum-minimum) value along the specified axis from a given matrix.
# Here 0 represents along column, 1 represents row.
# Store it in another variable
rslt = gvn_matrx.ptp(0)
# Print the peek-to-peek value along the specified axis from a given matrix.
print("The peek-to-peek value along the specified axis from a given matrix:")
print(rslt)

Output:

The given matrix is:
[[ 2 4 1]
 [ 8 7 3]
 [10 9 5]]
The peek-to-peek value along the specified axis from a given matrix:
[[8 5 4]]

 

Python Numpy matrix.ptp() Function Read More »

Python Numpy matrix.put() 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.put() Function:

Using the matrix.put() method of the Numpy module, we can put(insert) the value by passing index and value in a given particular matrix.

Syntax:

 matrix.put(index, value)

Return Value:

A new matrix (after putting values ) is returned by the put() function.

Numpy matrix.put() Function in Python

For 2-Dimensional (2D) Matrix (Inserting an element at Multiple Indices)

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
  • Pass the index/indices(as a tuple) and value as arguments to the put() function and apply it to the given matrix
  • Here we passed multiple indices and the value gets inserted at corresponding indices of the tuple.
  • Store it in another variable
  • Print the given matrix after inserting an element at the multiple indices.
  • 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 arguments to it and store it in a variable
gvn_matrx = np.matrix('[2, 1; 6, 3]')
            
# Pass the index/indices(as a tuple) and value as an argument to the put() function and apply it to the given matrix
# Here we passed multiple indices and the value gets inserted at corresponding indices of the tuple.
# Store it in another variable
gvn_matrx.put((0, 2), 50)
# Print the given matrix after inserting an element at the multiple indices
print("The given matrix after inserting an element at the multiple indices:")
print(gvn_matrx)

Output:

The given matrix after inserting an element at the multiple indices:
[[50 1]
[50 3]]

Explanation:

Here it inserts 50 at the indices 0 and 2.

NOTE:

The matrix indices starts from '0'

For 3-Dimensional (3D) Matrix (Inserting an element at Single Index)

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
  • Pass the index and value as arguments to the put() function and apply it to the given matrix
  • Here we passed a single index and the value gets inserted at that corresponding index.
  • Store it in another variable
  • Print the given matrix after inserting an element at the given index.
  • 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('[2, 4, 1; 8, 7, 3; 10, 9, 5]')
            
# Pass the index and value as arguments to the put() function and apply it to the given matrix
# Here we passed single index and the value gets inserted at that corresponding index.
# Store it in another variable
gvn_matrx.put((4), 100)
# Print the given matrix after inserting an element at the given index.
print("The given matrix after inserting an element {100} at the given index{4}:")
print(gvn_matrx)

Output:

The given matrix after inserting an element {100} at the given index{4}:
[[ 2 4 1]
 [ 8 100 3]
 [ 10 9 5]]

 

 

Python Numpy matrix.put() Function Read More »

Python Numpy matrix.flatten() 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 in 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.flatten() Function:

We can flatten a given matrix using the matrix.flatten() method of the Numpy module, which returns a one-dimensional matrix as an output.

Syntax:

 matrix.flatten()

Return Value:

The flattened 1-Dimensional matrix from a given matrix is returned by the flatten() function.

What is a Flattened matrix?

Flattening a matrix means flattening the given n-dimensional matrix to a one-Dimensional(1D) matrix.

Example:

Let the matrix be:

[[ 1 2 3]
 [ 4 5 6]
 [ 7 8 9]]

Matrix after Flattening:

[1 2 3 4 5 6 7 8 9]

Numpy matrix.flatten() 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 flatten() function on the given matrix to get the flattened matrix from a given matrix.
  • Here, it flattens to a 1-Dimensional matrix.
  • Store it in another variable
  • Print the flattened matrix 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('[3, 2; 4, 5]')
            
# Apply flatten() function on the given matrix to get the flattened matrix from a given matrix.
# Here, it flattens to a 1-Dimensional matrix.
# Store it in another variable
rslt = gvn_matrx.flatten()
# Print the flattened matrix from a given matrix
print("The flattened matrix from a given matrix:")
print(rslt)

Output:

The flattened matrix from a given matrix:
[[3 2 4 5]]

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 flatten() function on the given matrix to get the flattened matrix from a given matrix.
  • Here, it flattens to a 1-Dimensional matrix.
  • Store it in another variable
  • Print the flattened matrix 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('[2, 4, 1; 8, 7, 3; 10, 9, 5]')

# Apply flatten() function on the given matrix to get the flattened matrix from a given matrix.
# Here, it flattens to a 1-Dimensional matrix.
# Store it in another variable
rslt = gvn_matrx.flatten()
# Print the flattened matrix from a given matrix
print("The flattened matrix from a given matrix:")
print(rslt)

Output:

The flattened matrix from a given matrix:
[[ 2 4 1 8 7 3 10 9 5]]

Python Numpy matrix.flatten() Function Read More »

Python Scipy stats.halfgennorm.entropy() 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.entropy() Function:

We can obtain the value of entropy of a random variate by using the stats.halfgennorm.entropy() function.

Syntax:

stats.halfgennorm.entropy(beta)

Return Value:

The entropy value of a random variate is returned by the stats.halfgennorm.entropy() Function.

What is Entropy?

When entropy is discussed in information theory, it refers to the randomness in data. Another way to think about entropy is as the data’s unpredictability. So a high entropy indicates that the data is scattered, whereas a low entropy indicates that nearly all of the data is the same.

Scipy stats.halfgennorm.entropy() Function in Python

Method #1: Using entropy 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.
  • Calculate the entropy value using the entropy() function of halfgennorm by passing the given beta value as an argument to it.
  • Store it in another variable.
  • Print the entropy value 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

# Calculate the entropy value using the entropy() function of halfgennorm by passing
# the given beta value as an argument to it.
# Store it in another variable.
rslt = halfgennorm.entropy(gvn_beta)

# Print the entropy value for the given beta value
print("The entropy value for the given beta {", gvn_beta,"} value = ", rslt)

Output:

The entropy value for the given beta { 3 } value = 0.22014169159299057

Method #2: Using entropy 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.
  • Calculate the entropy value using the entropy() function of halfgennorm by passing the given beta value as an argument to it.
  • Store it in another variable.
  • Print the entropy value 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 = "))

# Calculate the entropy value using the entropy() function of halfgennorm by passing
# the given beta value as an arguments to it.
# Store it in another variable.
rslt = halfgennorm.entropy(gvn_beta)

# Print the entropy value for the given beta value
print("The entropy value for the given beta {", gvn_beta,"} value = ", rslt)

Output:

Enter some random number = 5
The entropy value for the given beta { 5 } value = 0.1146259099966842

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

Python sympy.Matrix.col() 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.col() Method:

The columns of the matrix can be extracted using the sympy.Matrix().col() method.

Syntax:

 sympy.Matrix().col()

Return Value:

The column values of a given matrix are returned by the sympy.Matrix().col() function.

sympy.Matrix.col() 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 and apply col() function on it by passing the column number as an argument to it to get the values of the specified column.
  • Here it gives the values of the 0th column.
  • Store it in a variable
  • Print the values of the specified column.
  • 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 and apply col() function on it by 
# passing the column number as an argument to it to get the values of the specified column.
# Here it gives the values of 0th column.
# Store it in a variable
col_values = Matrix([[3, 2], [8, 7]]).col(0)

# Print the values of the specified column
print("The values of the 0th column:")
print(col_values)

Output:

The values of the 0th column:
Matrix([[3], [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 and apply col() function on it by passing the column number as an argument to it to get the values of the specified column.
  • Here it gives the values of the 1st column.
  • Store it in a variable
  • Print the values of the specified column.
  • 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 and apply col() function on it by 
# passing the column number as an argument to it to get the values of the specified column.
# Here it gives the values of 1st column.
# Store it in a variable
col_values = Matrix([[1, 6, 10], [8, 7, 5], [3, 2, 9]]).col(1)

# Print the values of the specified column
print("The values of the 1st column:")
print(col_values)

Output:

The values of the 1st column:
Matrix([[6], [7], [2]])

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

Python sympy.Matrix.col_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.col_del() Method:

We can delete the columns of a matrix using the sympy.Matrix.col_del() function.

Syntax:

 sympy.Matrix().col_del()

Return Value:

A new matrix after the deletion of the column is returned by the Matrix.col_del() function.

sympy.Matrix.col_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 col_del() function on the above-given matrix by passing the column number as an argument to it
    to delete the values of the specified column.
  • Here it deletes the zero(0th) column.
  • Print the given matrix after deleting the zero(0th) column.
  • 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 col_del() function on the above given matrix by passing the column number as an argument to it
# to delete the values of the specified column.
# Here it deletes the zero(0th) column.
gvn_matrx.col_del(0)

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

Output:

The given matrix after deleting the zero(0th) column:
Matrix([[5], [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 col_del() function on the above-given matrix by passing the column number as an argument to it
    to delete the values of the specified column.
  • Here it deletes the 1st column.
  • Print the given matrix after deleting the 1st column.
  • 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 col_del() function on the above given matrix by passing the column number as an argument to it
# to delete the values of the specified column.
# Here it deletes the 1st column.
gvn_matrx.col_del(1)

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

Output:

The given matrix after deleting the 1st column:
Matrix([[1, 10], [8, 5], [3, 9]])

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

Python sympy.expand_log() 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.expand_log() Method:

We can use expand_log() function of the sympy module to simplify the log terms in the mathematical equation by employing the properties stated below:

  •  log(x*y)=log(x)+log(y)
  •  log(x**n)=nlog(x)

Syntax:

  sympy.expand_log()

Return Value:

The simplified mathematical expression is returned by the expand_log() function.

sympy.expand_log() Method in Python

Example1

Here it gives the result based on the log(x*y)=log(x)+log(y) property.

Approach:

  • Import all the functions from sympy module using the import keyword
  • Pass the symbols to be used and set positive as True as arguments to the symbols() function and store them in corresponding variables.
  • Give the mathematical expression as static input and store it in a variable.
  • Pass the above-given expression as an argument to the expand_log() method to simplify the log terms in the given expression based on the properties given.
  • Here it gives the result based on the log(x*y)=log(x)+log(y) property.
  • Store it in another variable.
  • Print the result after the simplification of log terms in the given expression.
  • The Exit of the Program.

Below is the implementation:

# Import all the functions from sympy module using the import keyword
from sympy import *
# Pass the symbols to be used and set positive as True as arguments to the 
# symbols() function and store them in corresponding variables.
a, b, c = symbols('a b c', positive = True)
# Give the mathematical expression as static input and store it in a variable.
gvn_expression = log(a * b)
    
# Pass the above given expression as an argument to the expand_log() method 
# to simplify the log terms in the given expression based on the properties given.
# Store it in another variable.
rslt = expand_log(gvn_expression)

# Print the result after the simplification of log terms in the given expression.
print(rslt)

Output:

log(a) + log(b)

Example2

Here it gives the result based on the log(x**n)=nlog(x) property.

Approach:

  • Import all the functions from sympy module using the import keyword
  • Pass the symbols to be used and set positive as True as arguments to the symbols() function and store them in corresponding variables.
  • Give the mathematical expression as static input and store it in a variable.
  • Pass the above-given expression as an argument to the expand_log() method to simplify the log terms in the given expression based on the properties given.
  • Here it gives the result based on the log(x**n)=nlog(x) property.
  • Store it in another variable.
  • Print the result after the simplification of log terms in the given expression.
  • The Exit of the Program.

Below is the implementation:

# Import all the functions from sympy module using the import keyword
from sympy import *
# Pass the symbols to be used and set set positive as True as arguments to the 
# symbols() function and store them in corresponding variables.
a, b, c = symbols('a b c', positive = True)
# Give the mathematical expression as static input and store it in a variable.
gvn_expression = log(b**2)
    
# Pass the above given expression as an argument to the expand_log() method 
# to simplify the log terms in the given expression based on the properties given.
# Here it gives the result based on the log(x**n)=nlog(x) property.
# Store it in another variable.
rslt = expand_log(gvn_expression)

# Print the result after the simplification of log terms in the given expression.
print(rslt)

Output:

2*log(b)

Python sympy.expand_log() Method Read More »

Python sympy.coeff(x, n) 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.coeff(x, n) Method:

We can determine the coefficient of variables in mathematical expressions using the coeff(x, n) method of the sympy module.

Syntax:

 sympy.coeff(x, n)

Return Value:

The coefficient of variables is returned by the coeff() function.

sympy.coeff(x, n) Method in Python

Example1

Here it gives the coefficient of x^2 in the given mathematical expression i.e, 1+3 = 4

Approach:

  • Import all the functions from sympy module using the import keyword
  • Pass the symbols to be used as arguments to the symbols() function and store them in corresponding variables.
  • Give the mathematical expression as static input and store it in a variable.
  • Pass the variable and power as arguments to the coeff() method and apply it to the given expression to get the coefficient of the given mathematical expression.
  • Here it gives the coefficient of x^2 i.e, 1+3 = 4
  • Store it in another variable.
  • Print the coefficient of x^2 in the given mathematical expression.
  • The Exit of the Program.

Below is the implementation:

# Import all the functions from sympy module using the import keyword
from sympy import *

# Pass the symbols to be used as arguments to the symbols() function
# and store them in corresponding variables.
x, y, z = symbols('x y z')

# Give the mathematical expression as static input and store it in a variable.
gvn_expression = x**2+3*y**2+3*x**2+x+y

# Pass the variable and power as arguments to the coeff() method and apply it on the
# given expression to get the coefficient of given mathematical expression.
# Here it gives the coefficient of x^2 i.e, 1+3 = 4
# Store it in another variable.
rslt = gvn_expression.coeff(x, 2)

# Print the coefficient of x^2 in the given mathematical expression.
print("The coefficient of x^2 in the given mathematical expression is:")
print(rslt)

Output:

The coefficient of x^2 in the given mathematical expression is:
4

Example2

Here it gives the coefficient of y^3 in the given mathematical expression i.e, 1+6-1 = 6

Approach:

  • Import all the functions from sympy module using the import keyword
  • Pass the symbols to be used as arguments to the symbols() function and store them in corresponding variables.
  • Give the mathematical expression as static input and store it in a variable.
  • Pass the variable and power as arguments to the coeff() method and apply it to the given expression to get the coefficient of the given mathematical expression.
  • Here it gives the coefficient of y^3 i.e, 1+6-1 = 6
  • Store it in another variable.
  • Print the coefficient of y^3 in the given mathematical expression.
  • The Exit of the Program.

Below is the implementation:

# Import all the functions from sympy module using the import keyword
from sympy import *

# Pass the symbols to be used as arguments to the symbols() function
# and store them in corresponding variables.
x, y, z = symbols('x y z')

# Give the mathematical expression as static input and store it in a variable.
gvn_expression = y**3+5*x**2+6*y**3+x-y**3+z

# Pass the variable and power as arguments to the coeff() method and apply it to the
# given expression to get the coefficient of given mathematical expression.
# Here it gives the coefficient of y^3 i.e, 1+6-1 = 6
# Store it in another variable.
rslt = gvn_expression.coeff(y, 3)

# Print the coefficient of y^3 in the given mathematical expression.
print("The coefficient of y^3 in the given mathematical expression is:")
print(rslt)

Output:

The coefficient of y^3 in the given mathematical expression is:
6

Python sympy.coeff(x, n) Method Read More »