Python

Python loc() Function: To Extract Values from a Dataset

Python loc() Function:

Python is made up of modules that provide built-in functions for dealing with and manipulating data values.

Pandas is an example of such a module.

The Pandas module allows us to manage enormous data sets including a massive amount of data for processing all at once.

This is where Python’s loc() method comes into play. The loc() function makes it simple to retrieve data values from a dataset.

The loc() function allows us to obtain the data values fitted in a specific row or column based on the index value given to the function.

Syntax:

pandas.DataFrame.loc[index label]

We must supply the index values for which we want the whole data set to be shown in the output.

The index label could be one of the following values:

  • Single label – for example: String
  • List of string
  • Slice objects with labels
  • List of an array of labels, etc.

Using the loc() function, we may extract a specific record from a dataset depending on the index label.

If the provided index is not present as a label it returns KeyError.

Example

# Import pandas module using the import keyword
import pandas as pd
# Pass the some random list of data given to the DataFrame() function and store it in a variable
gvn_data = pd.DataFrame([[110, 2, 25, 14], [100, 3, 22, 10], [115, 1, 27, 9], [90, 5, 12, 14]],
     index=['Almond Delight', 'Clusters', 'Corn Chex', 'Cocoa Puffs'],
     columns=['calories', 'vitamins', 'fats','carboydrates'])
# Print the above dataframe
print("The given input Dataframe: ")
print(gvn_data)

Output:

The given input Dataframe: 
                calories  vitamins  fats  carboydrates
Almond Delight       110         2    25            14
Clusters             100         3    22            10
Corn Chex            115         1    27             9
Cocoa Puffs           90         5    12            14

Extraction of a Row from the Given Dataframe

Get all of the data values linked with the index label ‘clusters’ as shown below:

print(gvn_data.loc['Clusters'])
# Import pandas module using the import keyword
import pandas as pd
# Pass the some random list of data given to the DataFrame() function and store it in a variable
gvn_data = pd.DataFrame([[110, 2, 25, 14], [100, 3, 22, 10], [115, 1, 27, 9], [90, 5, 12, 14]],
     index=['Almond Delight', 'Clusters', 'Corn Chex', 'Cocoa Puffs'],
     columns=['calories', 'vitamins', 'fats','carboydrates'])
# Get all of the data values linked with the index label 'Clusters' using the
# loc[] function and print it.
print(gvn_data.loc['Clusters'])

Output:

calories        100
vitamins          3
fats             22
carboydrates     10
Name: Clusters, dtype: int64

Extraction of Multiple Rows from the Given Dataframe

We cal also get the multiple rows from the given dataframe.

Get all of the data values linked with the index labels ‘clusters’,  ‘Almond Delight’ as shown below:

print(gvn_data.loc[['Clusters', 'Almond Delight']])
# Import pandas module using the import keyword
import pandas as pd
# Pass the some random list of data given to the DataFrame() function and store it in a variable
gvn_data = pd.DataFrame([[110, 2, 25, 14], [100, 3, 22, 10], [115, 1, 27, 9], [90, 5, 12, 14]],
     index=['Almond Delight', 'Clusters', 'Corn Chex', 'Cocoa Puffs'],
     columns=['calories', 'vitamins', 'fats','carboydrates'])
# Extracting multiple rows from the given dataframe.
# Get all of the data values linked with the index labels 'clusters',  'Almond Delight'
# using the loc[] function and print it.
print(gvn_data.loc[['Clusters', 'Almond Delight']])

Output:

                calories  vitamins  fats  carboydrates
Clusters             100         3    22            10
Almond Delight       110         2    25            14

Extraction of Range of Rows from the Given Dataframe

We can retrieve data values of the range of rows using the loc[] function and slicing operator as shown below:

print(gvn_data.loc['Clusters': 'Cocoa Puffs'])
# Import pandas module using the import keyword
import pandas as pd
# Pass the some random list of data given to the DataFrame() function and store it in a variable
gvn_data = pd.DataFrame([[110, 2, 25, 14], [100, 3, 22, 10], [115, 1, 27, 9], [90, 5, 12, 14]],
     index=['Almond Delight', 'Clusters', 'Corn Chex', 'Cocoa Puffs'],
     columns=['calories', 'vitamins', 'fats','carboydrates'])
# Extracting range of rows from the given dataframe.
# Get all of the data values linked with the index labels 'clusters' to 'Cocoa Puffs '
# using the loc[] function,slicing operator and print it.
print(gvn_data.loc['Clusters': 'Cocoa Puffs'])

Output:

             calories  vitamins  fats  carboydrates
Clusters          100         3    22            10
Corn Chex         115         1    27             9
Cocoa Puffs        90         5    12            14

 

Python loc() Function: To Extract Values from a Dataset Read More »

In Python, How do you subset a DataFrame?

In this article, we will go through numerous methods for subsetting a dataframe. If you are importing data into Python then you must be aware of Data Frames. A DataFrame is a two-dimensional data structure in which data is aligned in rows and columns in a tabular form.

We may do various operations on a DataFrame using the Pandas library. We can even construct and access a DataFrame subset in several formats.

subsetting:

The process of picking a set of desired rows and columns from a data frame is known as subsetting.

We have the following options to select:

  • All rows and only a few columns(limited columns)
  • All columns and only a few rows
  • A limited number of rows and columns

Subsetting a data frame is useful since it allows you to access only a portion of the data frame. When you wish to reduce the number of parameters in your data frame, this comes in helpful.

Let us take a cereal dataset as an example.

Importing and Getting first 5 rows of the Dataset

Import the dataset into a Pandas Dataframe.

Apply head() function to the above dataset to get the first 5 rows.

cereal_dataset.head()
# Import pandas module as pd using the import keyword
import pandas as pd
# Import dataset using read_csv() function by pasing the dataset name as
# an argument to it.
# Store it in a variable.
cereal_dataset = pd.read_csv('cereal.csv')
# Apply head() function to the above dataset to get the first 5 rows.
cereal_dataset.head()

Output:

namemfrtypecaloriesproteinfatsodiumfibercarbosugarspotassvitaminsshelfweightcupsrating
0100% BranNC704113010.05.062802531.00.3368.402973
1100% Natural BranQC12035152.08.08135031.01.0033.983679
2All-BranKC70412609.07.053202531.00.3359.425505
3All-Bran with Extra FiberKC504014014.08.003302531.00.5093.704912
4Almond DelightRC110222001.014.08-12531.00.7534.384843

Using the Indexing Operator, select a subset of a dataframe.

The Indexing Operator is simply another term for square brackets. Using just the square brackets, you can select columns, rows, or a combination of rows and columns.

1)Selection of Only Columns

Use the below line of code to choose a column using the indexing operator.

cereal_dataset['vitamins']

The above line of code selects the column with the label ‘vitamins’ and displays all row values associated with it.

# Import pandas module as pd using the import keyword
import pandas as pd
# Import dataset using read_csv() function by pasing the dataset name as
# an argument to it.
# Store it in a variable.
cereal_dataset = pd.read_csv('cereal.csv')
# Apply head() function to the above dataset to get the first 5 rows.
cereal_dataset.head()
# Get all the rows values corresponding to the 'vitamins' column in the 
# above given dataset
cereal_dataset['vitamins']

Output:

0     25
1      0
2     25
3     25
4     25
      ..
72    25
73    25
74    25
75    25
76    25
Name: vitamins, Length: 77, dtype: int64

Selection of Multiple Columns

Select multiple columns using the index Operator.
Get all the rows values corresponding to the ‘vitamins’, ‘fat’ columns in the above-given dataset
cereal_dataset[['vitamins', 'fat']]
# Import pandas module as pd using the import keyword
import pandas as pd
# Import dataset using read_csv() function by pasing the dataset name as
# an argument to it.
# Store it in a variable.
cereal_dataset = pd.read_csv('cereal.csv')
# Apply head() function to the above dataset to get the first 5 rows.
cereal_dataset.head()
# Select multiple columns using the index Operator.
# Get all the rows values corresponding to the 'vitamins','fat' columns in the 
# above given dataset
cereal_dataset[['vitamins', 'fat']]

Output:

vitaminsfat
0251
105
2251
3250
4252
72251
73251
74251
75251
76251

77 rows × 2 columns

It generates a separate data frame that is a subset of the original.

2)Selection of Rows

The indexing operator can be used to pick specific rows depending on specified conditions.

To pick rows with ‘vitamins’ greater than 50, use the code below:

vitmns_grtrthan50= cereal_dataset[cereal_dataset['vitamins']>50]
vitmns_grtrthan50

Output:

namemfrtypecaloriesproteinfatsodiumfibercarbosugarspotassvitaminsshelfweightcupsrating
38Just Right Crunchy NuggetsKC110211701.017.066010031.01.0036.523683
39Just Right Fruit & NutKC140311702.020.099510031.30.7536.471512
53Product 19KC100303201.020.034510031.01.0041.503540
69Total Corn FlakesGC110212000.021.033510031.01.0038.839746
70Total Raisin BranGC140311904.015.01423010031.51.0028.592785
71Total Whole GrainGC100312003.016.0311010031.01.0046.658844

Using Python.loc(), select a Subset of a dataframe.

The.loc indexer is a powerful tool for selecting rows and columns from a data frame. It can also be used to select both rows and columns at the same time.

Note: It’s vital to understand that.loc() function only works on the labels of rows and columns. Following that, we’ll look at.iloc(), which is based on a row and column index.

 1)Selection of a Row using loc():

Use the following code to choose a single row with.loc().

cereal_dataset.loc[2]
# Import pandas module as pd using the import keyword
import pandas as pd
# Import dataset using read_csv() function by pasing the dataset name as
# an argument to it.
# Store it in a variable.
cereal_dataset = pd.read_csv('cereal.csv')
# Get all the 2nd rows values in the above given dataset using the loc[] function
cereal_dataset.loc[2]

Output:

name        All-Bran
mfr                K
type               C
calories          70
protein            4
fat                1
sodium           260
fiber              9
carbo              7
sugars             5
potass           320
vitamins          25
shelf              3
weight             1
cups            0.33
rating       59.4255
Name: 2, dtype: object

 Selection of Multiple Rows using loc():

cereal_dataset.loc[[2,4,6]]
# Import pandas module as pd using the import keyword
import pandas as pd
# Import dataset using read_csv() function by pasing the dataset name as
# an argument to it.
# Store it in a variable.
cereal_dataset = pd.read_csv('cereal.csv')
# Retrieving Multiple rows data
# Get all the 2, 4, 6 rows values in the above given dataset using the loc[] function
cereal_dataset.loc[[2, 4, 6]]

Output:

namemfrtypecaloriesproteinfatsodiumfibercarbosugarspotassvitaminsshelfweightcupsrating
2All-BranKC70412609.07.053202531.00.3359.425505
4Almond DelightRC110222001.014.08-12531.00.7534.384843
6Apple JacksKC110201251.011.014302521.01.0033.174094

Getting Range of Rows:

We can get rows data by providing the range (lower and upper limits) using slicing and loc[] function.

cereal_dataset.loc[3:6]
# Import pandas module as pd using the import keyword
import pandas as pd
# Import dataset using read_csv() function by pasing the dataset name as
# an argument to it.
# Store it in a variable.
cereal_dataset = pd.read_csv('cereal.csv')
# Retrieving Multiple rows data
# Get 3 to 6 rows data by providing the range (lower and upper limits) 
# using slicing and loc[] function.
cereal_dataset.loc[3:6]

Output:

namemfrtypecaloriesproteinfatsodiumfibercarbosugarspotassvitaminsshelfweightcupsrating
3All-Bran with Extra FiberKC504014014.08.003302531.00.5093.704912
4Almond DelightRC110222001.014.08-12531.00.7534.384843
5Apple Cinnamon CheeriosGC110221801.510.510702511.00.7529.509541
6Apple JacksKC110201251.011.014302521.01.0033.174094

2)Selection of rows and columns using loc()

Use the below line of code to choose specific rows and columns from the given data frame:

cereal_dataset.loc[3:6,['vitamins',' fats']]
# Import pandas module as pd using the import keyword
import pandas as pd
# Import dataset using read_csv() function by pasing the dataset name as
# an argument to it.
# Store it in a variable.
cereal_dataset = pd.read_csv('cereal.csv')
# Retrieving Multiple rows data
# Get vitamins, fat columns from 3 to 6 rows by providing the range (lower and upper limits)
# and columns using slicing and loc[] function.
cereal_dataset.loc[3:6,['vitamins', 'fat']]

Output:

vitaminsfat
3250
4252
5252
6250

Using Python.iloc(), select a Subset of a dataframe.

The iloc() function stands for integer location. It is completely based on integer indexing for both rows and columns.

Using iloc saves you from having to write down the entire label for each row and column.

Use iloc() to choose a subset of rows and columns as shown below:

cereal_dataset.iloc[[1,4,5], [2, 6]]

The above code selects rows 1, 4, and 5, as well as columns 2 and 6.

# Import pandas module as pd using the import keyword
import pandas as pd
# Import dataset using read_csv() function by pasing the dataset name as
# an argument to it.
# Store it in a variable.
cereal_dataset = pd.read_csv('cereal.csv')
# Retrieving Multiple rows data
# Get rows 1, 4, and 5, as well as columns 2 and 6 using iloc[] function.
cereal_dataset.iloc[[1,4,5], [2, 6]]

Output:

typesodium
1C15
4C200
5C180

After replacing the labels with integers, you can use iloc() to pick rows or columns individually, much like loc().

In Python, How do you subset a DataFrame? Read More »

Python Program for Coefficient of Determination – R Squared Value

Before delving into the topic of Coefficient of Determination, it is important to grasp the importance of evaluating a machine learning model using error metrics.

To solve any model in the field of Data Science, the developer must first analyze the efficiency of the model before applying it to the dataset. The model is evaluated using specific error metrics. One such error metric is the coefficient of determination.

Coefficient of Determination:

The coefficient of determination, often known as the R2 score. It is used to evaluate the performance of a linear regression model.

It is the degree of variation in the output-dependent attribute that can be predicted based on the input independent variable (s). It is used to determine how effectively the model reproduces observed results, based on the ratio of total deviation of results explained by the model.

R square has a range between [0,1].

Formula

R2= 1- SSres / SStot

where.

SSres: SSres is the sum of the squares of the residual errors of the data model’s
SStot: The total sum of the errors is represented by SStot.

Note: The higher the R square value, the better the model and the outcomes.

R2 With Numpy

Example:

Approach:

  • Import numpy module using the import keyword.
  • Give the list of actual values as static input and store it in a variable.
  • Give the list of predicted values as static input and store it in another variable.
  • Pass the given actual, predicted lists as the arguments to the corrcoef() function to get the Correlation Matrix.
  • Slice the matrix with the indexes [0,1] to get the value of R, also known as the Coefficient of Correlation.
  • Store it in another variable.
  • Calculate the value of R**2(R square) and store it in another variable.
  • Print the value of R square.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy
# Give the list of actual values as static input and store it in a variable.
actul_vals = [5, 1, 7, 2, 4]
# Give the list of predicted values as static input and store it in another
# variable.
predctd_vals = [4, 1.5, 2.8, 3.7, 4.9]
# Pass the given actual, predicted lists as the arguments to the corrcoef()
# function to get the Correlation Matrix
correltn_matrx = numpy.corrcoef(actul_vals, predctd_vals)
# Slice the matrix with the indexes [0,1] to get the value of R, also known
# as the Coefficient of Correlation.
rsltcorretn = correltn_matrx[0, 1]
# Calculate the value of R**2(R square) and store it in another variable.
Rsqure = rsltcorretn**2
# Print the value of R square
print("The result value of R square = ",Rsqure)

Output:

The result value of R square = 0.09902230080299725

R2 With Sklearn Library

The Python sklearn module has an r2_score() function for calculating the coefficient of determination.

Example

Approach:

  • Import r2_score function from sklearn.metrics module using the import keyword.
  • Give the list of actual values as static input and store it in a variable.
  • Give the list of predicted values as static input and store it in another variable.
  • Pass the given actual, predicted lists as the arguments to the r2_score() function to get the value of the coefficient of determination(R square).
  • Print the value of R square(coefficient of determination).
  • The Exit of the Program.

Below is the implementation:

# Import r2_score function from sklearn.metrics module using the import keyword. 
from sklearn.metrics import r2_score 
# Give the list of actual values as static input and store it in a variable.
actul_vals = [5, 1, 7, 2, 4]
# Give the list of predicted values as static input and store it in another
# variable.
predctd_vals = [4, 1.5, 2.8, 3.7, 4.9]
# Pass the given actual, predicted lists as the arguments to the r2_score()
# function to get the value of the coefficient of determination(R square).
Rsqure = r2_score(actul_vals, predctd_vals)
# Print the value of R square(coefficient of determination)
print("The result value of R square = ",Rsqure)

Output:

The result value of R square = 0.009210526315789336

Python Program for Coefficient of Determination – R Squared Value Read More »

Python Program for sample() Function with Examples

When handling problems involving data prediction, we frequently encounter scenarios in which we must test the algorithm on a small set of data to evaluate the method’s accuracy.

This is where the Python sample() function comes into play.

For operations, we may use the sample() method to select a random sample from the available data. Though there are other strategies for sampling data, the sample() method is widely regarded as one of the most simple.

Python’s sample() method works with all sorts of iterables, including list, tuple, sets, dataframes, and so on. It selects data from the iterable at random from the user-specified number of data values.

sample() Function:

sample() is a built-in function of Python’s random module that returns a specific length list of items taken from a sequence, such as a list, tuple, string, or set. Used for random sampling Non-replacement.

Syntax:

random.sample(sequence, k)

Parameters:

sequence: It may be a list, tuple, string, or set, etc.

k: It is an Integer. This is the length of a sample.

Return Value:

Returns a new list of k elements selected from the sequence.

Examples:

1)For Lists

Approach:

  • Import sample() function from the random module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Give the length of the sample as static input and store it in another variable.
  • Pass the given list, sample length as the arguments to the sample() method to get the given length(len_sampl) of random sample items from the list.
  • Store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import sample() function from the random module using the import keyword.
from random import sample
# Give the list as static input and store it in a variable.
gvn_lst = [24, 4, 5, 9, 2, 1]
# Give the length of the sample as static input and store it in another variable.
len_sampl = 3
# Pass the given list, sample length as the arguments to the sample() method
# to get given length(len_sampl) of random sample items from the list
# Store it in another variable.
rslt = sample(gvn_lst, len_sampl)
# Print the above result.
print("The", len_sampl, "random items from the given list are:")
print(rslt)

Output:

The 3 random items from the given list are:
[9, 24, 4]
2)For Sets

Approach:

  • Import sample() function from the random module using the import keyword.
  • Give the set as static input and store it in a variable.
  • Give the length of the sample as static input and store it in another variable.
  • Pass the given set, sample length as the arguments to the sample() method to get the given length(len_sampl) of random sample items from the set.
  • Store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import sample() function from random module using the import keyword.
from random import sample
# Give the set as static input and store it in a variable.
gvn_set = {2, 4, 7, 1, 3, 1, 4, 2}
# Give the length of sample as static input and store it in another variable.
len_sampl = 4
# Pass the given set, sample length as the arguments to the sample() method
# to get given length(len_sampl) of random sample items from the set
# Store it in another variable.
rslt = sample(gvn_set, len_sampl)
# Print the above result.
print("The", len_sampl, "random items from the given set are:")
print(rslt)

Output:

The 4 random items from the given set are:
[1, 4, 7, 2]
Exceptions & Errors While using the sample() Function

When working with the sample() function, we may see a ValueError exception. This exception is thrown if the sample length is greater than the length of the iterable.

For Example:

# Import sample() function from the random module using the import keyword.
from random import sample
# Give the list as static input and store it in a variable.
gvn_lst = [24, 4, 5, 9, 2, 1]
# Give the length of the sample as static input and store it in another variable.
len_sampl = 10
# Pass the given list, sample length as the arguments to the sample() method
# to get given length(len_sampl) of random sample items from the list
# Store it in another variable.
rslt = sample(gvn_lst, len_sampl)
# Print the above result.
print("The", len_sampl, "random items from the given list are:")
print(rslt)

Output:

Traceback (most recent call last):
  File "/home/f39024cad259bfac4456fa81ec86fb82.py", line 10, in <module>
    rslt = sample(gvn_lst, len_sampl)
  File "/usr/lib/python3.6/random.py", line 320, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative

 

Python Program for sample() Function with Examples Read More »

In Python, How can you Plot and Customize a Pie Chart?

A pie chart is a circular statistical picture graph divided into slices to show numerical proportions. The arc length of each slice in a pie chart is proportionate to the quantity it represents.

The area of the wedge is defined by the length of the wedge’s arc. The area of a wedge represents the percentage of that part of the data in relation to the entire data set. Pie charts are widely used in corporate presentations to provide a brief review of topics such as sales, operations, survey data, and resources.

Pie charts are a common technique to display poll results.

Creating data

# Give some random list(fruits) as static input and store it in a variable.
fruit_lst = ["Apple", "mango", "banana", "orange", "grapes"]
# Give the percentage list as static input and store it in another variable.
gvn_percentges = [20, 15, 40, 10, 15]

How to Create a Pie Chart?

Matplotlib will be used to create a Pie-Chart.

In its pyplot module, the Matplotlib API offers a pie() method that generates a pie chart based on the data in an array.

Syntax:

matplotlib.pyplot.pie(data, explode=None, labels=None, colors=None, 
autopct=None, shadow=False)

Parameters

data: The array of data values to be plotted is represented by data, and the fractional area of each slice is represented by data/sum (data). If sum(data)<1 returns the fractional area directly, the resulting pie will have an empty wedge of size 1-sum (data).

labels: It is a list of string sequences that sets the label of each wedge.

colour: The colour attribute is used to give the colour of the wedge.

autopct: This is a string that is used to name each wedge with its numerical value.

shadow: The shadow is utilised to generate the shadow of the wedge.

To create a basic Pie-chart, we need labels and the values that go with those labels.

Example

Approach:

  • Import matplotlib.pyplot module as plt using the import keyword.
  • Give some random list(fruits) as static input and store it in a variable.
  • Give the percentage(size) list as static input and store it in another variable.
  • Get the subplots using the subplots function and assign it to two different variables.
  • Pass the given percentages(size)list, labels to the pie() function and apply it to the above axis (where labels is the fruit list).
  • Show the piechart using the show() function.
  • The Exit of the Program.

Below is the implementation:

# Import matplotlib.pyplot module as plt using the import keyword.
import matplotlib.pyplot as plt
# Give some random list(fruits) as static input and store it in a variable.
fruit_lst = ["Apple", "mango", "banana", "orange", "grapes"]
# Give the percentage list as static input and store it in another variable.
gvn_percentges = [20, 15, 40, 10, 15]
# Get the subplots using the subplots function and assign it to two different
# variables
figre, axis = plt.subplots()
# Pass the given percentages(size)list, labels to the pie() function
# and apply it to the above axis where labels is the fruit list.
axis.pie(gvn_percentges, labels=fruit_lst)
axis.axis('equal')
# Show the piechart using the show() function.
plt.show()

Output:

 

Customize a Pie Chart

A pie chart can be altered in a variety of ways. The startangle attribute spins the plot by the provided number of degrees in a counterclockwise direction on the pie chart’s x-axis. The shadow attribute accepts a boolean value; if true, the shadow appears below the rim of the pie. Wedges of the pie can be customized using wedgeprop, which accepts a Python dictionary as an argument and returns a list of name-value pairs specifying wedge attributes such as linewidth, edgecolor, and so on. A frame is drawn around the pie chart by setting frame=True axis. The percentages displayed on the wedges are controlled by autopct.

How to Make a slice pop-out?

Using the explode option, you can make one or more pie-chart slices pop out.

To do this give an array with the explosion values. The explosion array provides the fraction of the radius by which to offset each slice.

Example

# Import matplotlib.pyplot module as plt using the import keyword.
import matplotlib.pyplot as plt
# Give some random list(fruits) as static input and store it in a variable.
fruit_lst = ["Apple", "mango", "banana", "orange", "grapes"]
# Give the percentage list as static input and store it in another variable.
gvn_percentges = [20, 15, 40, 10, 15]
#  Give the explode values as static input and store it in another variable.
explode_vals = (0.1, 0, 0.2, 0, 0)
# Get the subplots using the subplots function and assign it to two different
# variables
figre, axis = plt.subplots()
# Pass the given percentages(size)list, explode values, and labels to the pie() function
# and apply it to the above axis (where labels is the fruit list).
axis.pie(gvn_percentges, explode=explode_vals, labels=fruit_lst)
# Show the piechart using the show() function.
plt.show()

Output:

Rotating the Pie-chart

By defining a strartangle, you can rotate the pie-chart.

It rotates the start of the pie chart by the specified number of degrees counterclockwise from the x-axis.

Example

# Import matplotlib.pyplot module as plt using the import keyword.
import matplotlib.pyplot as plt
# Give some random list(fruits) as static input and store it in a variable.
fruit_lst = ["Apple", "mango", "banana", "orange", "grapes"]
# Give the percentage list as static input and store it in another variable.
gvn_percentges = [20, 15, 40, 10, 15]
#  Give the explode values as static input and store it in another variable.
explode_vals = (0.1, 0, 0.2, 0, 0)
# Get the subplots using the subplots function and assign it to two different
# variables
figre, axis = plt.subplots()
# Rotate the pie chart by giving the startangle.
axis.pie(gvn_percentges, explode=explode_vals, labels=fruit_lst,
        shadow=True, startangle=90)
# Show the piechart using the show() function.
plt.show()

Output:

 

To Display the percentages

Display the percentages using the autopct.
# Import matplotlib.pyplot module as plt using the import keyword.
import matplotlib.pyplot as plt
# Give some random list(fruits) as static input and store it in a variable.
fruit_lst = ["Apple", "mango", "banana", "orange", "grapes"]
# Give the percentage list as static input and store it in another variable.
gvn_percentges = [20, 15, 40, 10, 15]
#  Give the explode values as static input and store it in another variable.
explode_vals = (0.1, 0, 0.2, 0, 0)
# Get the subplots using the subplots function and assign it to two different
# variables
figre, axis = plt.subplots()
# Display the percentages using the autopct
axis.pie(gvn_percentges, explode=explode_vals, labels=fruit_lst,
        autopct='%1.1f%%',shadow=True, startangle=90)
# Show the piechart using the show() function.
plt.show()

Output:

 

Color customization or Changing

Matplotlib allows you to be creative and make your pie-chart as colorful as possible.

To modify the colors of your pie chart, give the colors list and apply those colors to the pie chart by giving it as an argument to the pie function().

# Import matplotlib.pyplot module as plt using the import keyword.
import matplotlib.pyplot as plt
# Give some random list(fruits) as static input and store it in a variable.
fruit_lst = ["Apple", "mango", "banana", "orange", "grapes"]
# Give the percentage list as static input and store it in another variable.
gvn_percentges = [20, 15, 40, 10, 15]
# Give the colors as static input and store it in another variable.
gvn_colors = ("pink", "yellow", "skyblue", "grey", "green")
# Give the explode values as static input and store it in another variable. 
explode_vals = (0.1, 0, 0.2, 0, 0)
figre, axis = plt.subplots()
# Applying the above given colors to the pie chart.
axis.pie(gvn_percentges, colors = gvn_colors, explode=explode_vals, labels=fruit_lst,
        autopct='%1.1f%%',shadow=True, startangle=90)
# Show the piechart using the show() function.
plt.show()

Output:

 

To Display the Color Codes

Along with your pie-chart, you can display a box containing the pie-color chart’s scheme. This is very beneficial if your pie chart has a lot of pieces.

Display the color codes using the legend() function.

Example

# Import matplotlib.pyplot module as plt using the import keyword.
import matplotlib.pyplot as plt
# Give some random list(fruits) as static input and store it in a variable.
fruit_lst = ["Apple", "mango", "banana", "orange", "grapes"]
# Give the percentage list as static input and store it in another variable.
gvn_percentges = [20, 15, 40, 10, 15]
# Give the colors as static input and store it in another variable.
gvn_colors = ("pink", "yellow", "skyblue", "grey", "green")
# Give the explode values as static input and store it in another variable. 
explode_vals = (0.1, 0, 0.2, 0, 0)
figre, axis = plt.subplots()
# Customized pie chart
axis.pie(gvn_percentges, colors = gvn_colors, explode=explode_vals, labels=fruit_lst,
        autopct='%1.1f%%',shadow=True, startangle=90)
patches, texts, auto = axis.pie(gvn_percentges, colors = gvn_colors, explode=explode_vals, labels=fruit_lst,
        autopct='%1.1f%%',shadow=True, startangle=90)
# Display the color codes using the legend() function
plt.legend(patches, labels, loc="best")
# Show the piechart using the show() function.
plt.show()

Output:

 

In Python, How can you Plot and Customize a Pie Chart? Read More »

In Python, How Do you Save a Dataframe as a csv File?

Pandas Module in Python:

Pandas is an open-source library based on the NumPy library. It enables users to perform effective data analysis, cleaning, and preparation. Pandas is fast, and it provides users with high performance and productivity.

The majority of the datasets you work with are referred to as DataFrames. DataFrames is a 2-Dimensional labeled Data Structure containing indexes for rows and columns, and each cell can store any form of value. DataFrames are simply Dictionary-based NumPy Arrays.

Creating a Dataframe

Approach:

  • Import os module using the import keyword.
  • Import pandas module using the import keyword.
  • Give some random list(fruits) as static input and store it in a variable.
  • Create a dictionary for the list of the above fruits and store it in another variable.
  • Pass the above fruit_dictnry as an argument to the pandas.DataFrame() function to create a dataframe for the above dictionary.
  • Print the above-obtained dataframe.
  • The Exit of the Program.

Below is the implementation:

# Import os module using the import keyword.
import os
# Import pandas module using the import keyword.
import pandas
# Give some random list(fruits) as static input and store it in a variable.
fruit_lst = ["Apple", "mango", "banana", "orange", "grapes", "Kiwi"]
# Create a dictionary for the above fruits list and store it in another variable.
fruit_dictnry = {'Types of Fruits': fruit_lst}
# Pass the above fruit_dictnry as an argument to the pandas.DataFrame() function
# to create a dataframe for the above dictionary.
rslt_dataframe = pandas.DataFrame(fruit_dictnry)
# Print the above obtained dataframe.
print(rslt_dataframe)

Output:

 Types of Fruits
0           Apple
1           mango
2          banana
3          orange
4          grapes
5            Kiwi

How to Save this Dataframe?

We frequently encounter circumstances in which we need to save large amounts of data generated by scraping or analysis in an easy, accesible  and readable form rather shareable form.

We can achieve this now by storing the data frame as a csv file.

dataframe.to_csv('filename.csv')

We can save a data frame as a CSV file using the pandas.to_csv() function. The file name must be passed as a parameter to the method.

Example

Approach:

  • Import os module using the import keyword.
  • Import pandas module using the import keyword.
  • Give some random list(fruits) as static input and store it in a variable.
  • Create a dictionary for the list of the above fruits and store it in another variable.
  • Pass the above fruit_dictnry as an argument to the pandas.DataFrame() function to create a dataframe for the above dictionary.
  • Save the above dataframe as a CSV file using the to_csv() function by passing some random file name as an argument that you want to save with.
  • Now the file will be saved as a csv file.
  • The Exit of the Program.

Below is the implementation:

from pandas.core.frame import DataFrame
# Import os module using the import keyword.
import os
# Import pandas module using the import keyword.
import pandas
# Give some random list(fruits) as static input and store it in a variable.
fruit_lst = ["Apple", "mango", "banana", "orange", "grapes", "Kiwi"]
# Create a dictionary for the above fruits list and store it in another variable.
fruit_dictnry = {'Types of Fruits': fruit_lst}
# Pass the above fruit_dictnry as an argument to the pandas.DataFrame() function
# to create a dataframe for the above dictionary.
rslt_dataframe = pandas.DataFrame(fruit_dictnry)
# Save the above dataframe as a CSV file using the to_csv() function by passing 
# some random file name as an argument that you want to save with.
rslt_dataframe.to_csv('fruits.csv')

Output:

Types of Fruits
0Apple
1mango
2banana
3orange
4grapes
5Kiwi

 

In Python, How Do you Save a Dataframe as a csv File? Read More »

Python Bar Plot: Visualization of Categorical Data

Data visualization allows us to analyze the data and examine the distribution of data in a pictorial way.

We may use BarPlot to visualize the distribution of categorical data variables. They depict a discrete value distribution. As a result, it reflects a comparison of category values.

The x-axis shows discrete values, whereas the y axis represents numerical values of comparison and vice versa.

BarPlot with Matplotlib

The Python matplotlib package includes a number of functions for plotting data and understanding the distribution of data values.

To construct a Bar plot with the matplotlib module, use the matplotlib.pyplot.bar() function.

Syntax:

matplotlib.pyplot.bar(x, height, width, bottom, align)

Parameters

x: The barplot’s scalar x-coordinates

height: It is the height of the bars to be plotted.

width: This is optional. It is the width of the bars to be plotted.

bottom: It is the vertical baseline.

align: This is optional. It is the type of bar plot alignment.

Example:

Approach:

  • Import matplotlib.pyplot module as plt using the import keyword.
  • Give some random list(gadgets) as static input and store it in a variable.
  • Give the other list(cost) as static input and store it in another variable.
  • Pass the given two lists as the arguments to the plt.bar() function to get the barplot of those lists.
  • Show the barplot of the given two lists using the show() function.
  • The Exit of the Program.

Below is the implementation:

# Import matplotlib.pyplot module using the import keyword.
import matplotlib.pyplot as plt
# Give some random list(gadgets) as static input and store it in a variable.
gadgets = ['mobile', 'fridge', 'washingmachine', 'tab', 'headphones']
# Give the other list(cost) as static input and store it in another variable.
costs = [15000, 20000, 18000, 5000, 2500]
# Pass the given two lists as the arguments to the plt.bar() function
# to get the barplot of those lists.
plt.bar(gadgets, costs)
# Show the barplot of the given two lists using the show() function.
plt.show()

Output:

                                       

BarPlot with Seaborn Library

Plots are mostly used to depict the relationship between variables. These variables can be entirely numerical or represent a category such as a group, class, or division. This article discusses categorical variables and how to visualize them using Python’s Seaborn package.

Seaborn, in addition to being a statistical plotting toolkit, includes various default datasets.

The Python Seaborn module is built on top of the Matplotlib module and provides us with some advanced functionalities for better data visualization.

Syntax:

seaborn.barplot(x, y)

Example:

Approach:

  • Import seaborn module using the import keyword.
  • Import matplotlib.pyplot module as plt using the import keyword.
  • Import dataset using read_csv() function by passing the dataset name as an argument to it.
  • Store it in a variable.
  • Pass the id, calories columns, and above dataset as the arguments to the seaborn.barplot() function to get the barplot of those.
  • Display the barplot of the using the show() function.
  • The Exit of the Program.

Below is the implementation:

# Import seaborn module using the import keyword.
import seaborn
# Import matplotlib.pyplot module as plt using the import keyword.
import matplotlib.pyplot as plt
# Import dataset using read_csv() function by passing the dataset name as
# an argument to it.
# Store it in a variable.
dummy_dataset = pd.read_csv('dummy_data.csv')
# Pass the id, calories columns and above dataset as the arguments to the 
# seaborn.barplot() function to get the barplot of those.
seaborn.barplot(x="id", y="calories", data=dummy_dataset)
# Display the barplot of the using the show() function.
plt.show()

Output:

Python Bar Plot: Visualization of Categorical Data Read More »

Python Program to Solve the Replace and Remove Problem

Replace and Remove problem:

The name of the problem is Replace and Remove Problem, and we will be replacing one specific character with a different string as well as removing a specific character from the user’s input.

So we know we need to replace one character with another string or set of characters and remove one character from the input. The two rules that we will abide by are as follows:

  1. Replace a with double d (dd)
  2. Remove any occurrence of b

Examples:

Example1:

Input:

Given String = "pythonarticlesbinarybooks"

Output:

Original String =  pythonarticlesbinarybooks
The result string =  pythonddrticlesinddryooks

Example2:

Input:

Given string ="haaabbcdcj"

Output:

Original String = haaabbcdcj
The result string = hddddddbcdcj

Program to Solve the Replace and Remove Problem in Python

Below are the ways to solve the replace and remove problem in Python:

Approach:

Convert the given string to list and Traverse the list check if the character is equal to ‘a’ if it is equal modify the list element with dd else check if the character is equal to ‘b’ then remove the element from the list.Join all elements of the list and print it.

Method #1: Using For loop (Static Input)

Approach:

  • Give the input string as static input and store it in a variable.
  • Convert the given string to a list using the list() function and store it in a variable.
  • Calculate the length of the list using the len() function and store it in a variable.
  • Loop till the length of the given list using the for loop.
  • Check if the list element at the iterator index is equal to a using the if conditional statement.
  • If it is true then replace the list element at iterator index with ‘dd’.
  • Loop in the above list using the For loop and in operator.
  • Check if the element is equal to ‘b’ using the if conditional statement.
  • If it is true then remove the element from the list using the remove() function.
  • After the end of for loop.
  • Convert the list to string using the join() function.
  • Print the string after joining the list elements.
  • The Exit of the Program.

Below is the implementation:

# Give the input string as static input and store it in a variable.
gvnstrng = 'pythonarticlesbinarybooks'
# Convert the given string to a list using the list() function and store it in a variable.
strnglist = list(gvnstrng)
# Calculate the length of the list using the len() function and store it in a variable.
lstlengt = len(strnglist)
# Loop till the length of the given list using the for loop.
for indx in range(lstlengt):
        # Check if the list element at the iterator index is equal to a
    # using the if conditional statement.
    if(strnglist[indx] == 'a'):
        # If it is true then replace the list element at iterator index with 'dd'.
        strnglist[indx] = 'dd'
# loop in the above list using the For loop and in operator
for ele in strnglist:
    # check if the element is equal to 'b' using the if conditional statement.
    if(ele == 'b'):
        # If it is true then remove the element from the list using the remove() function.
        strnglist.remove(ele)


# After the end of for loop.
# Convert the list to string using the join() function.
rststrng = ''.join(strnglist)
# Print the string after joining the list elements.
print('Original String = ', gvnstrng)
print('The result string = ', rststrng)

Output:

Original String =  pythonarticlesbinarybooks
The result string =  pythonddrticlesinddryooks

Method #2: Using For loop (User Input)

Approach:

  • Give the input string as user input using list(),map(),split(),int() functions and store it in a variable.
  • Convert the given string to a list using the list() function and store it in a variable.
  • Calculate the length of the list using the len() function and store it in a variable.
  • Loop till the length of the given list using the for loop.
  • Check if the list element at the iterator index is equal to a using the if conditional statement.
  • If it is true then replace the list element at iterator index with ‘dd’.
  • Loop in the above list using the For loop and in operator.
  • Check if the element is equal to ‘b’ using the if conditional statement.
  • If it is true then remove the element from the list using the remove() function.
  • After the end of for loop.
  • Convert the list to string using the join() function.
  • Print the string after joining the list elements.
  • The Exit of the Program.

Below is the implementation:

# Give the input string as user input using list(),map(),split(),int() functions and store it in a variable.
gvnstrng = input('Give some random string = ')
# Convert the given string to a list using the list() function and store it in a variable.
strnglist = list(gvnstrng)
# Calculate the length of the list using the len() function and store it in a variable.
lstlengt = len(strnglist)
# Loop till the length of the given list using the for loop.
for indx in range(lstlengt):
        # Check if the list element at the iterator index is equal to a
    # using the if conditional statement.
    if(strnglist[indx] == 'a'):
        # If it is true then replace the list element at iterator index with 'dd'.
        strnglist[indx] = 'dd'
# loop in the above list using the For loop and in operator
for ele in strnglist:
    # check if the element is equal to 'b' using the if conditional statement.
    if(ele == 'b'):
        # If it is true then remove the element from the list using the remove() function.
        strnglist.remove(ele)


# After the end of for loop.
# Convert the list to string using the join() function.
rststrng = ''.join(strnglist)
# Print the string after joining the list elements.
print('Original String = ', gvnstrng)
print('The result string = ', rststrng)

Output:

Give some random string = haaabbcdcj
Original String = haaabbcdcj
The result string = hddddddbcdcj

Python Program to Solve the Replace and Remove Problem Read More »

Python Program to Capture Screenshots

There are numerous approaches to capture the screenshots in Python.

Python includes a number of libraries for capturing screenshots. In this article, let us look at a handful of these libraries and their implementation using Python code.

1)By Using pyautogui module

The pyautogui module employs the screenshot function, which is in charge of capturing a snapshot of the entire computer screen. The save function is then utilized to save the screenshot to our device.

2) By using pillow Module

An ImageGrab submodule is used by the pillow module. This method necessitates the capture of a region, which necessitates the setting of the region’s diagonal coordinates.

Then we use the grab function, which takes the region parameters and uses them to capture the screenshot. Finally, use the save function to save the taken image.

Before going to the coding part, install the pyautogui module in your system as shown below:

pip install pyautogui

Output:

Collecting pyautogui Downloading PyAutoGUI-0.9.53.tar.gz (59 kB) 
|████████████████████████████████| 59 kB 3.7 MB/s Collecting pymsgbox 
Downloading PyMsgBox-1.0.9.tar.gz (18 kB) Installing build dependencies ... 
done Getting requirements to build wheel ... done Preparing wheel metadata ... 
done Collecting PyTweening>=1.0.1 Downloading pytweening-1.0.4.tar.gz (14 kB) 
Collecting pyscreeze>=0.1.21 Downloading PyScreeze-0.1.28.tar.gz (25 kB) 
Installing build dependencies ... done Getting requirements to build wheel ... 
done Preparing wheel metadata ... done Collecting pygetwindow>=0.0.5 Downloading
 PyGetWindow-0.0.9.tar.gz (9.7 kB) Collecting mouseinfo Downloading MouseInfo-0.1
.3.tar.gz (10 kB) Collecting python3-Xlib Downloading python3-xlib-0.15.tar.gz 
(132 kB) |████████████████████████████████| 132 kB 18.8 MB/s Collecting pyrect 
Downloading PyRect-0.1.4.tar.gz (15 kB) Requirement already satisfied: Pillow>=5
.2.0 in /usr/local/lib/python3.7/dist-packages (from pyscreeze>=0.1.21->
pyautogui) (7.1.2) Collecting pyperclipBuilding wheel for pyrect (setup.py) ...
done Created wheel for pyrect: filename=PyRect-0.1.4-py2.py3-none-any.whl size=95
47 sha256=ed4a10cef4885f276a3067e64ab033e9507adea168952f5ce4636cb3a6f6d12e 
Stored in directory: /root/.cache/pip/wheels/97/5f/8e/6f26a5b00d46679ee2391a3542
334274ce8bdaf7c6b0f3504c Building wheel for python3-Xlib (setup.py) ... done
Created wheel for python3-Xlib: filename=python3_xlib-0.15-py3-none-any.whl 
size=109517 sha256=9844de06645f2fc25ed8ae389ad41da84bbe8ed102c6013ce3b88c10c
5e216df Stored in directory: /root/.cache/pip/wheels/67/6f/f2/18f51230840318
e784c45e1392a0e174777e499251e42ddf86 Successfully built pyautogui pygetwindow
pyscreeze PyTweening mouseinfo pymsgbox pyperclip pyrect python3-Xlib 
Installing collected packages: python3-Xlib, pyrect, pyperclip, PyTweening, 
pyscreeze, pymsgbox, pygetwindow, mouseinfo, pyautogui Successfully installed 
PyTweening-1.0.4 mouseinfo-0.1.3 pyautogui-0.9.53 pygetwindow-0.0.9 pymsgbox-1
.0.9 pyperclip-1.8.2 pyrect-0.1.4 pyscreeze-0.1.28 python3-Xlib-0.15

Method #1: Using Built-in Functions (Static Input)

1)By Using pyautogui module

Approach:

  • Import pyautogui module using the import keyword.
  • Take the screenshot using the pyautogui.screenshot() function and store it in a variable
  • Save the above screenshot using the save() function
  • The Exit of the Program.

Below is the implementation:

# Import pyautogui module using the import keyword.
import pyautogui
# Take the screenshot using the pyautogui.screenshot() function and 
# store it in a variable
scrnsht = pyautogui.screenshot()
# Save the above screenshot using the save() function
scrnsht.save("SS1.jpg")

2) By using pillow Module

Approach:

  • Import ImageGrab function from PIL module using the import keyword.
  • Give the diagonal coordinates as static input and store it in a variable.
  • Pass the above given diagonal coordinates to the ImageGrab.grab() function to take a screenshot and store it in another variable.
  • Save the above screenshot using the save() function.
  • The Exit of the Program.

Below is the implementation:

# Import ImageGrab function from PIL module using the import keyword.
from PIL import ImageGrab
# Give the diagonal coordinates as static input and store it in a variable
diagnl_cordnates = (200, 200, 400, 400)
# Pass the above given diagonal coordinates to the ImageGrab.grab() function
# to take a screenshot and store it in another variable
scrnsht = ImageGrab.grab(diagnl_cordnates)
# Save the above screenshot using the save() function.
scrnsht.save("myscreenshot.jpg")

 

 

Python Program to Capture Screenshots Read More »

Python Program to How to Check if two Stacks are Equal

Stack:

Stacking objects means putting them on top of one another in the English language. This data structure allocates memory in the same manner.

Data structures are essential for organizing storage in computers so that humans can access and edit data efficiently. Stacks were among the first data structures to be defined in computer science. In layman’s terms, a stack is a linear accumulation of items. It is a collection of objects that provides fast last-in, first-out (LIFO) insertion, and deletion semantics. It is a modern computer programming and CPU architecture array or list structure of function calls and parameters. Elements in a stack are added or withdrawn from the top of the stack is a “last in, first out” order, similar to a stack of dishes at a restaurant.

Unlike lists or arrays, the objects in the stack do not allow for random access

Given two stacks the task is to check whether the given two stacks are equal or not in Python.

Examples:

Example1:

Input:

Given First Stack = [1,3,4,5]
Given Second Stack = [1,3,4,5]

Output:

The Given two stacks are equal

Example2:

Input:

Given First Stack = [1,3,4,3]
Given Second Stack = [1,3,4,5]

Output:

The Given two stacks are not equal

Program to How to Check if two Stacks are Equal in Python

Below are the ways to check the given two stacks are equal or not in Python:

Method #1: Using While Loop (Static Input)

Approach:

  • Give the first stack as static input and store it in a variable.
  • Give the second stack as static input and store it in another variable.
  • Create a function checkEqualStacks() which accepts the given two stacks and returns True if the given two stacks are equal else it returns False.
  • Inside the checkEqualStacks().
  • Check if the length of the first stack is not equal to the length of the second stack using the if conditional statement.
  • If their lengths are not equal then return False.
  • Loop till the length of the first stack using the while loop.
  • Check if the top elements of the given two stacks are equal using the if conditional statement.
  • If they are equal remove the top elements from the two stacks using the pop() function.
  • Else return False.
  • After the end of the while loop return True.
  • Inside the main function
  • Pass the given two stacks to the checkEqualStacks() function and check whether it returns True or False using the If conditional statement.
  • If the above If conditional statement is true then the given two stacks are equal.
  • Else the given two stacks are not equal.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkEqualStacks() which accepts the given two stacks
# and returns True if the given two stacks are equal else it returns False.


def checkEqualStacks(stck1, stck2):
        # Inside the checkEqualStacks().
        # Check if the length of the first stack is not equal to the
    # length of the second stack using the if conditional statement.
    if(len(stck1) != len(stck2)):
                # If their lengths are not equal then return False.
        return False
        # Loop till the length of the first stack using the while loop.
    while(len(stck1)):
                # Check if the top elements of the given two stacks are equal
        # using the if conditional statement.
        if(stck1[-1] == stck1[-1]):
            stck1.pop()
            stck2.pop()
            # If they are equal remove the top elements from the two stacks
            # using the pop()function.

        else:
          # Else return False.
            return False
   # After the end of the while loop return True.
    return True


# Inside the main function
# Give the first stack as static input and store it in a variable.
gvnstack1 = [4, 9, 1, 2, 3]
# Give the second stack as static input and store it in another variable.
gvnstack2 = [4, 9, 1, 2, 3]
# Pass the given two stacks to the checkEqualStacks()
# function and check whether it returns True or False using the If conditional statement.
if(checkEqualStacks(gvnstack1, gvnstack2)):
        # If the above If conditional statement is true then the given two stacks are equal.
    print('The Given two stacks are equal')
else:
        # Else the given two stacks are not equal.
    print('The Given two stacks are not equal')

Output:

The Given two stacks are equal

Method #2: Using While loop (User Input)

Approach:

  • Give the first stack as user input using map(),int(),list(),split() functions and store it in a variable.
  • Give the second stack as user input using map(),int(),list(),split() functions and store it in another variable.
  • Create a function checkEqualStacks() which accepts the given two stacks and returns True if the given two stacks are equal else it returns False.
  • Inside the checkEqualStacks().
  • Check if the length of the first stack is not equal to the length of the second stack using the if conditional statement.
  • If their lengths are not equal then return False.
  • Loop till the length of the first stack using the while loop.
  • Check if the top elements of the given two stacks are equal using the if conditional statement.
  • If they are equal remove the top elements from the two stacks using the pop() function.
  • Else return False.
  • After the end of the while loop return True.
  • Inside the main function
  • Pass the given two stacks to the checkEqualStacks() function and check whether it returns True or False using the If conditional statement.
  • If the above If conditional statement is true then the given two stacks are equal.
  • Else the given two stacks are not equal.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkEqualStacks() which accepts the given two stacks
# and returns True if the given two stacks are equal else it returns False.


def checkEqualStacks(stck1, stck2):
        # Inside the checkEqualStacks().
        # Check if the length of the first stack is not equal to the
    # length of the second stack using the if conditional statement.
    if(len(stck1) != len(stck2)):
                # If their lengths are not equal then return False.
        return False
        # Loop till the length of the first stack using the while loop.
    while(len(stck1)):
                # Check if the top elements of the given two stacks are equal
        # using the if conditional statement.
        if(stck1[-1] == stck1[-1]):
            stck1.pop()
            stck2.pop()
            # If they are equal remove the top elements from the two stacks
            # using the pop()function.

        else:
          # Else return False.
            return False
   # After the end of the while loop return True.
    return True


# Inside the main function
# Give the first stack as user input using map(),int(),list(),split() functions and store it in a variable.
gvnstack1 = list(map(int,input('Enter some random elements of first stack = ').split()))
# Give the second stack as user input using map(),int(),list(),split() functions and store it in another variable.
gvnstack2 = list(map(int,input('Enter some random elements of second stack = ').split()))
# Pass the given two stacks to the checkEqualStacks()
# function and check whether it returns True or False using the If conditional statement.
if(checkEqualStacks(gvnstack1, gvnstack2)):
        # If the above If conditional statement is true then the given two stacks are equal.
    print('The Given two stacks are equal')
else:
        # Else the given two stacks are not equal.
    print('The Given two stacks are not equal')

Output:

Enter some random elements of first stack = 1 3 1 4 5 6
Enter some random elements of second stack = 1 3 1 4 5 6
The Given two stacks are equal

Python Program to How to Check if two Stacks are Equal Read More »