Author name: Vikram Chiluka

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 »

Python Yagmail Module with Examples

Yagmail Module:

In today’s world, almost every business has an internet presence. That is, they have an online presence in order to increase sales and market reach.

The email address of clients is one of the most common data elements collected by websites. We are frequently required to sign up for websites/portals with our email addresses.

In our email inboxes, we receive adverts or even sales/offers. They do not type and send emails to all of their consumers by hand. This suggests that the process of sending emails through the portal/application is automated in some way.

This is where the Python Yagmail module comes in handy. We may send emails to consumers using the Python Yagmail module by integrating the email module with our apps.

It sends emails in an automated and user-friendly manner using simple Gmail SMTP clients. We only need to offer a few more facts, such as an email address, the text of the email, and so on.

This module can be integrated as part of any retail or online application/portal; this is the module’s best use case.

Installation of Yagmail Module:

Before going into the python code, install the Yagmail module in your system as shown below:

pip install yagmail

Output:

Collecting yagmail Downloading yagmail-0.14.260-py2.py3-none-any.whl (16 kB)
Collecting premailer Downloading premailer-3.10.0-py2.py3-none-any.whl (19 kB)
Requirement already satisfied: cachetools in /usr/local/lib/python3.7/dist-
packages (from premailer->yagmail) (4.2.4) Collecting cssutils Downloading 
cssutils-2.3.0-py3-none-any.whl (404 kB) |████████████████████████████████| 
404 kB 10.6 MB/s Requirement already satisfied: requests in /usr/local/lib/python
3.7/dist-packages (from premailer->yagmail) (2.23.0) Collecting cssselect 
Downloading cssselect-1.1.0-py2.py3-none-any.whl (16 kB) Requirement already 
satisfied: lxml in /usr/local/lib/python3.7/dist-packages 
(from premailer->yagmail) (4.2.6) Requirement already satisfied: 
importlib-metadata in /usr/local/lib/python3.7/dist-packages 
(from cssutils->premailer->yagmail) (4.8.2) Requirement already satisfied: 
typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from 
importlib-metadata->cssutils->premailer->yagmail) (3.10.0.2) Requirement 
already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages 
(from importlib-metadata->cssutils->premailer->yagmail) (3.6.0) Requirement 
already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages 
(from requests->premailer->yagmail) (2021.10.8) Requirement already satisfied: 
idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->premailer
->yagmail) (2.10) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,
>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->premailer->
yagmail) (1.24.3) Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local
/lib/python3.7/dist-packages (from requests->premailer->yagmail) (3.0.4) 
Installing collected packages: cssutils, cssselect, premailer, yagmail 
Successfully installed cssselect-1.1.0 cssutils-2.3.0 premailer-3.10.0 
yagmail-0.14.260

Import the yagmail module. Once imported, we’d need to give the Yagmail module an account to utilize for authentication and delivering emails to the recipient. That is, we create a user account for the module. By registering an email address, the module may quickly connect to the SMTP server and send emails.

Syntax:

yagmail.register('username', 'password')

If we do not want to include our sensitive data as a parameter, such as a password, we can create a.yagmail file and save your sensitive data in that file instead of exposing it directly as a parameter.
Now that we’ve registered the user, we can establish a secure connection with the SMTP client.

We can utilize the customizable command-line options listed below:

yagmail.SMTP('username', 'receiver1', 'receiver2', 'subject', 'body')

Parameters:

username: The email address of the sender
receiver: This contains the email address of the recipient/receiver. We can enter several email addresses for the receiver here.
subject: A brief headline for the email
body: Email message content

If we do not indicate the recipient’s email address, the email is sent to the sender’s address.

We proceed with the delivery of the content to the receiver’s email address after the content is complete.

Yagmail gives us the send() function for this purpose. Here, we pack and encapsulate all of the material, as well as the receiver’s information, as well as the subject and body line.

yagmail.send(to = [receiver1, receiver2, etc], subject=subject, contents=body)

Yagmail Module with Examples in Python

 

Method #1: Using Yagmail Module (Static Input)

Approach:

  • Import the yagmail module using the import keyword.
  • Pass the username, password, host as the arguments to the yagmail.SMTP() function.
  • Store it in a variable.
  • Give the receiver’s address as static input and store it in another variable.
  • Give the subject as static input and store it in another variable.
  • Give the body of the email as static input and store it in another variable.
  • Pass the given receiver’s address, subject, and body of the email as the arguments to the send() function.
  • Print some random text for acknowledgment.
  • The Exit of the Program.

Below is the implementation:

# Import the yagmail module using the import keyword.
import yagmail
# Pass the username, password, host as the arguments to the yagmail.SMTP() function.
# Store it in a variable.
source_mail = yagmail.SMTP(user='[email protected]',
                           password='userpassword', host='smtp.gmail.com')
# Give the receiver's address as static input and store it in another variable.
receiver_addrs = "[email protected]"
# Give the subject as static input and store it in another variable.
subjct = "Python Programs"
# Give the body of the email as static input and store it in another variable.
body_mail = ["hello welcome to Python Programs"]
# Pass the given receiver's address, subject, and body of the email as the arguments
# to the send() function.
source_mail.send(to=receiver_addrs, subject=subjct, contents=body_mail)
# Print some random text for acknowledgment.
print("The Email Sent Sucessfully")

Note:

Check that SMTP access is enabled for the email address you intend to use. 
Most email providers prohibit SMTP access by default to prevent unauthorized 
programs from abusing it.

 

 

Python Yagmail Module with Examples Read More »

Python Program to Perform Multiplication with Examples

Given two numbers and the task is to find the Multiplication of two numbers.

Also, given a list and the task is to find the Multiplication of all the elements in a given list.

Here we also use the Numpy module to perform the  Multiplication

Python numpy.prod() Function:

prod() in numpy accepts a list as an argument and returns the product of all the elements in the list. This function is quite useful and saves a significant amount of code. To use numpy.prod(), simply import numpy().

Examples:

Example1:

Input:

Given first number = 2
Given second number = 3

Output:

The Multiplication of given two numbers { 2 * 3 } =  6

Example2:

Input:

Given List = [4, 7, 3, 1, 5]

Output:

The Multiplication of all the elements of a given list [4, 7, 3, 1, 5] = 
420

Program to Perform Multiplication in Python with Examples

 

Method #1: Using (*) Operator (Static Input)

1) Multiplication using Functions

Approach:

  • Create a function say Multof_2numbers() which accepts the given two numbers as the arguments and returns the Multiplication of the given two numbers.
  • Inside the function, multiply the given two numbers and store it in a variable.
  • Return the above result.
  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Pass the given two numbers as the arguments to the Multof_2numbers() function and store it in another variable.
  • Print the Multiplication of given two numbers
  • The Exit of the program.

Below is the implementation:

# Create a function say Multof_2numbers() which accepts the given two numbers
# as the arguments and returns the Multiplication of given two numbers.


def Multof_2numbers(gvn_num1, gvn_num2):
    # Inside the function, multiply the given two numbers and store it in a variable.
    rsltmult = gvn_num1 * gvn_num2
    # Return the above result.
    return(rsltmult)


# Give the first number as static input and store it in a variable.
gvn_num1 = 2
# Give the second number as static input and store it in another variable.
gvn_num2 = 3
# Pass the given two numbers as the arguments to the Multof_2numbers() function
# and store it in another variable.
fnl_mult = Multof_2numbers(gvn_num1, gvn_num2)
# Print the Multiplication of given two numbers
print(
    "The Multiplication of given two numbers {", gvn_num1, "*", gvn_num2, "} = ", fnl_mult)

Output:

The Multiplication of given two numbers { 2 * 3 } =  6

2)Multiplication of list Elements using for loop:

Approach:

  • Give the list as static input and store it in a variable.
  • Take a variable and initialize its value to 1.
  • Loop in the given list using the for loop.
  • Multiply the element of the given list to the above declared rslt_mul variable and store it in the same variable.
  • Print the Multiplication of all the elements of a given list.
  •  The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [4, 7, 3, 1, 5]
# Take a variable and initialize its value to 1.
rslt_mul = 1
# Loop in the given list using the for loop.
for elemnt in gvn_lst:
    # Multiply the element of the given list to the above declared rslt_mul variable
    # and store it in the same variable.
    rslt_mul = rslt_mul * elemnt
# Print the Multiplication of all the elements of a given list.
print("The Multiplication of all the elements of a given list", gvn_lst, "= ")
print(rslt_mul)

Output:

The Multiplication of all the elements of a given list [4, 7, 3, 1, 5] = 
420

3)Using numpy.prod() Function

Approach:

  • Give the list as static input and store it in a variable.
  • Import numpy module using the import keyword.
  • Pass the given list as an argument to the numpy.prod() function to get the multiplication of all the elements of a given list.
  • Store it in another variable.
  • Print the Multiplication of all the elements of a given list.
  • The Exit of the program.

Below is the implementation:

# Import numpy module using the import keyword.
import numpy
# Give the list as static input and store it in a variable.
gvn_lst = [10, 2, 4]
# Pass the given list as an argument to the numpy.prod() function to get
# the multiplication of all the elements of a given list.
# Store it in another variable.
rslt_mul = numpy.prod(gvn_lst)
# Print the Multiplication of all the elements of a given list.
print("The Multiplication of all the elements of a given list", gvn_lst, "= ")
print(rslt_mul)

Output:

The Multiplication of all the elements of a given list [10, 2, 4] = 
80

Method #2: Using (*) Operator (User Input)

1) Multiplication using Functions

Approach:

  • Create a function say Multof_2numbers() which accepts the given two numbers as the arguments and returns the Multiplication of the given two numbers.
  • Inside the function, multiply the given two numbers and store it in a variable.
  • Return the above result.
  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Pass the given two numbers as the arguments to the Multof_2numbers() function and store it in another variable.
  • Print the Multiplication of given two numbers
  • The Exit of the program.

Below is the implementation:

# Create a function say Multof_2numbers() which accepts the given two numbers
# as the arguments and returns the Multiplication of given two numbers.


def Multof_2numbers(gvn_num1, gvn_num2):
    # Inside the function, multiply the given two numbers and store it in a variable.
    rsltmult = gvn_num1 * gvn_num2
    # Return the above result.
    return(rsltmult)


# Give the first number as user input using the int(input()) fucntion and store it in a variable.
gvn_num1 = int(input("Enter some random number = "))
# Give the second number as user input using the int(input()) fucntion and store it in another variable.
gvn_num2 = int(input("Enter some random number = "))
# Pass the given two numbers as the arguments to the Multof_2numbers() function
# and store it in another variable.
fnl_mult = Multof_2numbers(gvn_num1, gvn_num2)
# Print the Multiplication of given two numbers
print(
    "The Multiplication of given two numbers {", gvn_num1, "*", gvn_num2, "} = ", fnl_mult)

Output:

Enter some random number = 6
Enter some random number = 4
The Multiplication of given two numbers { 6 * 4 } = 24

2)Multiplication of list Elements using for loop:

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Take a variable and initialize its value to 1.
  • Loop in the given list using the for loop.
  • Multiply the element of the given list to the above declared rslt_mul variable and store it in the same variable.
  • Print the Multiplication of all the elements of a given list.
  •  The Exit of the program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
   
# Take a variable and initialize its value to 1.
rslt_mul = 1
# Loop in the given list using the for loop.
for elemnt in gvn_lst:
    # Multiply the element of the given list to the above declared rslt_mul variable
    # and store it in the same variable.
    rslt_mul = rslt_mul * elemnt
# Print the Multiplication of all the elements of a given list.
print("The Multiplication of all the elements of a given list", gvn_lst, "= ")
print(rslt_mul)

Output:

Enter some random List Elements separated by spaces = 2 3 6 4
The Multiplication of all the elements of a given list [2, 3, 6, 4] = 
144

3)Using numpy.prod() Function

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Import numpy module using the import keyword.
  • Pass the given list as an argument to the numpy.prod() function to get the multiplication of all the elements of a given list.
  • Store it in another variable.
  • Print the Multiplication of all the elements of a given list.
  • The Exit of the program.

Below is the implementation:

# Import numpy module using the import keyword.
import numpy
# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Pass the given list as an argument to the numpy.prod() function to get
# the multiplication of all the elements of a given list.
# Store it in another variable.
rslt_mul = numpy.prod(gvn_lst)
# Print the Multiplication of all the elements of a given list.
print("The Multiplication of all the elements of a given list", gvn_lst, "= ")
print(rslt_mul)

Output:

Enter some random List Elements separated by spaces = 5 2 3 1
The Multiplication of all the elements of a given list [5, 2, 3, 1] = 
30

Python Program to Perform Multiplication with Examples Read More »

Python collections Counter() Method with Examples

Counter():

The Counter class is a subset of the object data-set offered by Python3’s collections module. The Collections module exposes specialized container datatypes to the user, serving as an alternative to Python’s general-purpose built-ins such as dictionaries, lists, and tuples.

The counter is a subclass that counts hashable objects. When called, it constructs an iterable hash table implicitly.

elements() is a function of the Counter class that, when called on a Counter object, returns an itertool of all the known elements in the Counter object.

Parameters:

 It does not accept any parameters.

Return type:

 Returns an itertool for every element in the Counter object with a positive count.

Exceptions and Errors:

Because it returns an itertool rather than a specific data-container, it will output a garbage value when directly printed.
-> If an item's count has already been established in the Counter object, it will ignore items with zero and negative values.

Examples:

Example1:

Input:

Given String = "python-programs"

Output:

p  =  2
y  =  1
t  =  1
h  =  1
o  =  2
n  =  1
-  =  1
r  =  2
g  =  1
a  =  1
m  =  1
s  =  1

Example2:

Input:

Given List= [3, 1, 3, 4, 5, 6, 2, 2, 1, 5, 6, 9]

Output:

3  =  2
1  =  2
4  =  1
5  =  2
6  =  2
2  =  2
9  =  1

Collections Counter() Method with Examples in Python

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

i)elements() for string

Approach:

  • Import the Counter function from collections using the import keyword.
  • Give the string as static input and store it in a variable.
  • Apply the Counter() function for the string and store it in a variable(It returns a dictionary).
  • Apply elements() function for the Above result Counter Dictionary elements and print it.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter function from collections using the import keyword.
from collections import Counter
# Give the string as static input and store it in a variable.
gvnstrng = "python-programs"
# Apply the Counter() function for the string and store it in a
# variable(It returns a dictionary).
rslt = Counter(gvnstrng)
# Apply elements() function for the Above result Counter Dictionary elements and print it.
print(rslt.elements())

Output:

<itertools.chain object at 0x7f8599afb780>

ii)Printing elements of Counter(String)

Approach:

  • Import the Counter function from collections using the import keyword.
  • Give the string as static input and store it in a variable.
  • Apply the Counter() function for the string and store it in a variable(It returns a dictionary).
  • Loop in the elements of the Above result Counter Dictionary elements using for loop and elements() function.
  • Print the elements.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter function from collections using the import keyword.
from collections import Counter
# Give the string as static input and store it in a variable.
gvnstrng = "python-programs"
# Apply the Counter() function for the string and store it in a
# variable(It returns a dictionary).
rslt = Counter(gvnstrng)
# Loop in the elements of the Above result Counter Dictionary elements using for loop and elements() function.
for element in rslt.elements():
    # Print the elements.
    print(element)

Output:

p
p
y
t
h
o
o
n
-
r
r
g
a
m
s

iii)Printing elements with corresponding Frequency using elements()(String)

Approach:

  • Import the Counter function from collections using the import keyword.
  • Give the string as static input and store it in a variable.
  • Apply the Counter() function for the string and store it in a variable(It returns a dictionary).
  • Loop in the elements of the Above result Counter Dictionary elements using for loop and elements() function.
  • Print the elements and their frequency using the [] operator.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter function from collections using the import keyword.
from collections import Counter
# Give the string as static input and store it in a variable.
gvnstrng = "python-programs"
# Apply the Counter() function for the string and store it in a
# variable(It returns a dictionary).
rslt = Counter(gvnstrng)
# Loop in the elements of the Above result Counter Dictionary elements using for loop and elements() function.
for element in rslt.elements():
    # Print the elements and their frequency using the [] operator.
    print(element, ' = ', rslt[element])

Output:

p  =  2
p  =  2
y  =  1
t  =  1
h  =  1
o  =  2
o  =  2
n  =  1
-  =  1
r  =  2
r  =  2
g  =  1
a  =  1
m  =  1
s  =  1

iv)Printing elements with corresponding Frequency(List)

Approach:

  • Import the Counter function from collections using the import keyword.
  • Give the list as static input and store it in a variable.
  • Apply the Counter() function for the list and store it in a variable(It returns a dictionary).
  • Loop in the elements of the Above result Counter Dictionary elements using for loop .
  • Print the elements and their frequency using the [] operator.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter function from collections using the import keyword.
from collections import Counter
# Give the list as static input and store it in a variable.
gvllst = [3, 1, 3, 4, 5, 6, 2, 2, 1, 5, 6, 9]
# Apply the Counter() function for the list and store it in a
# variable(It returns a dictionary).
rslt = Counter(gvllst)
# Loop in the Above result Counter Dictionary elements using for loop.
for element in rslt:
    # Print the elements and their frequency using the [] operator.
    print(element, ' = ', rslt[element])

Output:

3  =  2
1  =  2
4  =  1
5  =  2
6  =  2
2  =  2
9  =  1

v)Printing elements with corresponding frequency(String)

Approach:

  • Import the Counter function from collections using the import keyword.
  • Give the string as static input and store it in a variable.
  • Apply the Counter() function for the string and store it in a variable(It returns a dictionary).
  • Loop in the elements of the Above result Counter Dictionary elements using for loop.
  • Print the elements and their frequency using the [] operator.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter function from collections using the import keyword.
from collections import Counter
# Give the string as static input and store it in a variable.
gvnstrng = "python-programs"
# Apply the Counter() function for the string and store it in a
# variable(It returns a dictionary).
rslt = Counter(gvnstrng)
# Loop in the elements of the Above result Counter Dictionary elements using for loop and elements() function.
for element in rslt:
    # Print the elements and their frequency using the [] operator.
    print(element, ' = ', rslt[element])

Output:

p  =  2
y  =  1
t  =  1
h  =  1
o  =  2
n  =  1
-  =  1
r  =  2
g  =  1
a  =  1
m  =  1
s  =  1

Method #2: Using Built-in Functions (User Input)

Approach:

  • Import the Counter function from collections using the import keyword.
  • Give the list as user input using map(),list(),input(),int() functions and store it in a variable.
  • Apply the Counter() function for the list and store it in a variable(It returns a dictionary).
  • Loop in the elements of the Above result Counter Dictionary elements using for loop .
  • Print the elements and their frequency using the [] operator.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter function from collections using the import keyword.
from collections import Counter
# Give the list as user input using map(),list(),input(),int() functions and store it in a variable.
gvllst = list(map(int, input('Enter some random elements = ').split()))
# Apply the Counter() function for the list and store it in a
# variable(It returns a dictionary).
rslt=Counter(gvllst)
# Loop in the Above result Counter Dictionary elements using for loop and elements() function.
for element in rslt:
    # Print the elements and their frequency using the [] operator.
    print(element, ' = ', rslt[element])

Output:

Enter some random elements = 7 1 2 1 8 9 2 4 6
7 = 1
1 = 2
2 = 2
8 = 1
9 = 1
4 = 1
6 = 1

Python collections Counter() Method with Examples Read More »

Python collections ChainMap() method with Examples

ChainMap():

Python has a container called “ChainMap” that combines many dictionaries into a single unit. ChainMap is part of the “collections” module.

Access Operations on ChainMap():

keys():

 This function displays all of the keys from all of the dictionaries in ChainMap.

values():

 This function displays the values of all dictionaries in ChainMap.

maps():

 This function is used to display all of the dictionaries in ChainMap's keys and values.

Collections ChainMap() method with Examples in Python

i)Implementing ChainMap

Approach:

  • Import the chainMap function from collections using the import keyword.
  • Give the dictionary with some random keys and values and store it in a variable.
  • Repeat the previous step for as many dictionaries as you choose.
  • Pass all the above dictionaries as arguments to chainMap() function and store it in a variable.
  • Print the Above Result.
  • The Exit of the Program.

Below is the Implementation:

# Import the chainMap function from collections using the import keyword.
from collections import ChainMap
# Give the dictionary with some random keys and values and store it in a variable.
dictnry1 = {'Good': 100, 'Morning': 448}
# Repeat the previous step for as many dictionaries as you choose.
dictnry2 = {'hello': 1300, 'this': 1448}
dictnry3 = {'is': 1070, 'Python-Programs': 4448}
# Pass all the above dictionaries as arguments to chainMap() function
# and store it in a variable.
reslt = ChainMap(dictnry1, dictnry2, dictnry3)
# Print the Above Result.
print('The final Result after applying ChainMap : ')
print(reslt)

Output:

The final Result after applying ChainMap : 
ChainMap({'Good': 100, 'Morning': 448}, {'hello': 1300, 'this': 1448}, {'is': 1070, 'Python-Programs': 4448})

ii)Implementing ChainMap Access Operations

Approach:

  • Import the chainMap function from collections using the import keyword.
  • Give the dictionary with some random keys and values and store it in a variable.
  • Repeat the previous step for as many dictionaries as you choose.
  • Pass all the above dictionaries as arguments to chainMap() function and store it in a variable say chainRslt.
  • Print the ChainMaps using the maps function.
  • Apply the maps method for the above result(chain) and print it.
  • To get All the keys in the chain we use the keys() method.
  • Apply the keys() function for the chainRslt and convert it to a list using the list() function.
  • Print the Above keys() list.
  • To get All the values  in the chain we use the values() method.
  • Apply the values () function for the chainRslt and convert it to a list using the list() function.
  • Print the Above values() list.
  • The Exit of the Program.

Below is the Implementation:

# Import the chainMap function from collections using the import keyword.
from collections import ChainMap
# Give the dictionary with some random keys and values and store it in a variable.
dictnry1 = {'hello': 100, 'this': 200}
# Repeat the previous step for as many dictionaries as you choose.
dictnry2 = {'this': 300, 'python-programs': 400}
# Pass all the above dictionaries as arguments to chainMap() function
# and store it in a variable say chainRslt.
chainRslt = ChainMap(dictnry1, dictnry2)
# Print the ChainMaps using the maps function.
# Apply the maps method for the above result(chain) and print it.
print('The Total Contents in the Chain Map are : ')
print(chainRslt.maps)

# To get All the keys in the chain we use the keys() method.
# Apply the keys() function for the chainRslt
# and convert it to a list using the list() function.
# Print the Above keys() list.
print('The keys present in Chain Map are : ')
print(list(chainRslt.keys()))
# To get All the values  in the chain we use the values() method.
# Apply the values () function for the chainRslt and convert it to a list using the list() function.
# Print the Above values() list.
print('The values present in Chain Map are : ')
print(list(chainRslt.values()))

Output:

The Total Contents in the Chain Map are : 
[{'hello': 100, 'this': 200}, {'this': 300, 'python-programs': 400}]
The keys present in Chain Map are : 
['python-programs', 'this', 'hello']
The values present in Chain Map are : 
[400, 200, 100]

Note:

The key "

this

" exists in both dictionaries, but only the first dictionary key
is used as the key value of "

this

". The dictionaries are ordered as they are
provided into the function.

Python collections ChainMap() method with Examples Read More »

Python collections defaultdict() Method with Examples

Defaultdict:

Defaultdict is a container similar to dictionaries seen in module collections. Defaultdict is a dictionary subclass that returns a dictionary-like object. Except for the fact that defualtdict never raises a KeyError, the behaviour of dictionaries and defualtdict is nearly identical. It gives a default value for a non-existent key.

Syntax:

defaultdict(default_factory)

Parameters:

default_factory:

A function that returns the dictionary's default value. 
If this parameter is missing, the dictionary will throw a KeyError.

Collections defaultdict() Method with Examples in Python

i)Default Dict Example

Approach:

  • Import the defaultdict from collections using the import keyword.
  • Create a function noKey() that returns some string/value if the key is not present in the dictionary.
  • Inside the function return some random statement(Related to Key is missing)
  • Create a dictionary by passing the above noKey() function as argument to defaultdict.
  • Give some random keys and values for the above dictionary.
  • Print the keys which are present in the dictionary.
  • Print the keys which are not present in the above dictionary then it prints the return value of the noKey() function.
  • The Exit of the Program.

Below is the implementation:

# Import the defaultdict from collections using the import keyword.
from collections import defaultdict
# Create a function noKey() that returns some string/value
# if the key is not present in the dictionary.


def noKey():
    # Inside the function return some random statement(Related to Key is missing)
    return "The Given Key is missing"


# Create a dictionary by passing the above noKey() function as argument to defaultdict.
defaultDictionary = defaultdict(noKey)
# Give some random keys and values for the above dictionary.
defaultDictionary["hello"] = 340
defaultDictionary["this"] = 400
defaultDictionary["is"] = 222
defaultDictionary["python-programs"] = 456

# Print the keys which are present in the dictionary.
print(defaultDictionary["hello"])
print(defaultDictionary["is"])
# Print the keys which are not present in the above dictionary
# then it prints the return value of the noKey() function.
print(defaultDictionary["good"])

Output:

340
222
The Given Key is missing

ii)__missing__() function in defaultDict

This function is used to set the dictionary’s default value. If the default_factory is None, a KeyError is generated; otherwise, the function returns a default value for the specified key. When the specified key cannot be found, the dict class’s __getitem__() method invokes this method. The value returned by the __missing__() method is raised or returned by __getitem__().

Approach:

  • Import the defaultdict from collections using the import keyword.
  • Create a dictionary by passing the lambda function as an argument to defaultdict.
  • Give some random keys and values for the above dictionary.
  • Pass the above keys to __missing__() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Import the defaultdict from collections using the import keyword.
from collections import defaultdict
# Create a dictionary by passing the lambda function as an argument to defaultdict.
defaultDictionary = defaultdict(lambda: "The Given Key is missing")
# Give some random keys and values for the above dictionary.
defaultDictionary["hello"] = 340
defaultDictionary["this"] = 400
defaultDictionary["is"] = 222
defaultDictionary["python-programs"] = 456
# Pass the above keys to __missing__() function and print it.
print(defaultDictionary.__missing__('hello'))
print(defaultDictionary.__missing__('this'))
print(defaultDictionary.__missing__('is'))
print(defaultDictionary.__missing__('python-programs'))

Output:

The Given Key is missing
The Given Key is missing
The Given Key is missing
The Given Key is missing

iii)Using List as default_factory

When the list class is specified as the default factory option, a defaultdict containing list values is generated.

Approach:

  • Import the defaultdict from collections using the import keyword.
  • Create a dictionary by passing the list as an argument to defaultdict.
  • Give some random keys and values for the above dictionary.
  • Print the dictionary.
  • The Exit of the Program.

Below is the implementation:

# Import the defaultdict from collections using the import keyword.
from collections import defaultdict
# Create a dictionary by passing the list as an argument to defaultdict.
defaultDictionary = defaultdict(list)
# Give some random keys and values for the above dictionary.
defaultDictionary["hello"] = 340
defaultDictionary["this"] = 400
defaultDictionary["is"] = 222
defaultDictionary["python-programs"] = 456
# Print the dictionary.
print(defaultDictionary)

Output:

defaultdict(<class 'list'>, {'hello': 340, 'this': 400, 'is': 222, 'python-programs': 456})

Python collections defaultdict() Method with Examples Read More »

Python collections OrderedDict() Method with Examples

OrderedDict:

An OrderedDict is a subclass of dictionary that remembers the order in which keys were first placed. The only distinction between dict() and OrderedDict() is:

The sequence in which the keys are inserted is preserved by OrderedDict. A standard dict does not keep track of the insertion order, therefore iterating through it returns the items in any order. OrderedDict, on the other hand, remembers the order in which the elements are placed.

Collections OrderedDict() Method with Examples in Python

i)OrderedDict vs Normal Dictionary Example

Approach:

  • Import the OrderedDict from collections using the import keyword.
  • Take a Empty dictionary using {} or dict() (Normal Dictionary).
  • Give some random keys and values for the above dictionary.
  • Take another dictionary using OrderedDict() (Ordered Dictionary).
  • Give the same keys and values for this dictionary.
  • Print the Normal Dictionary and Ordered Dictionary keys and Values.
  • We can see that the ordered is not maintained in Normal Dictionary but ordered is maintained in Ordered Dictionary.
  • The Exit of the Program.

Below is the Implementation:

# Import the OrderedDict from collections using the import keyword.
from collections import OrderedDict
# Take a Empty dictionary using {} or dict() (Normal Dictionary).
normalDict = {}
# Give some random keys and values for the above dictionary.
normalDict['hello'] = 100
normalDict['this'] = 400
normalDict['is'] = 500
normalDict['Python-Programs'] = 900
# Take another dictionary using OrderedDict() (Ordered Dictionary).
orderedDictionary = OrderedDict()
# Give the same keys and values for this dictionary.
orderedDictionary['hello'] = 100
orderedDictionary['this'] = 400
orderedDictionary['is'] = 500
orderedDictionary['Python-Programs'] = 900
# Print the Normal Dictionary and Ordered Dictionary keys and Values.
# We can see that the ordered is not maintained in Normal Dictionary but ordered is maintained in Ordered Dictionary.
print('Normal Dictionary :')
print(normalDict)
print('Ordered Dictionary : ')
print(orderedDictionary)

Output:

Normal Dictionary :
{'hello': 100, 'is': 500, 'this': 400, 'Python-Programs': 900}
Ordered Dictionary : 
OrderedDict([('hello', 100), ('this', 400), ('is', 500), ('Python-Programs', 900)])

ii)What happens if we change/modify key or value in Ordered Dictionary?

In OrderedDict, if the value of a key is altered, the key’s position remains unchanged.

Approach:

  • Import the OrderedDict from collections using the import keyword.
  • Take a dictionary using OrderedDict() (Ordered Dictionary).
  • Give some random keys and values for this dictionary.
  • Print the Dictionary before modification
  • Modify any key in the Above Dictionary by changing its value.
  • Print the Dictionary after modification
  • The Exit of the Program.

Below is the Implementation:

# Import the OrderedDict from collections using the import keyword.
from collections import OrderedDict

# Take a dictionary using OrderedDict() (Ordered Dictionary).
orderedDictionary = OrderedDict()
# Give some random keys and values for this dictionary.
orderedDictionary['hello'] = 100
orderedDictionary['this'] = 400
orderedDictionary['is'] = 500
orderedDictionary['Python-Programs'] = 900
# Print the Dictionary before modification
print('The given Dictionary Before Modification : ')
for key, value in orderedDictionary.items():
    print(key, value)
# Modify any key in the Above Dictionary by changing its value.
orderedDictionary['is'] = 1929
# Print the Dictionary after modification
print('The given Dictionary After Modification : ')
for key, value in orderedDictionary.items():
    print(key, value)

Output:

The given Dictionary Before Modification : 
hello 100
this 400
is 500
Python-Programs 900
The given Dictionary After Modification : 
hello 100
this 400
is 1929
Python-Programs 900

Explanation:

Here we can see that the order remains unchanged.

iii)What if we remove and reinsert the same key in Ordered Dictionary?

As OrderedDict maintains the order of insertion, deleting and re-inserting the same key will move it to the rear.

Approach:

  • Import the OrderedDict from collections using the import keyword.
  • Take a dictionary using OrderedDict() (Ordered Dictionary).
  • Give some random keys and values for this dictionary.
  • Print the Dictionary before Deleting the key.
  • Remove Some Random Key from the above dictionary using the pop() method.
  • Print the Dictionary after Deleting the key.
  • Insert the same key again to the Ordered Dictionary
  • Print the Dictionary after Reinserting the same key.
  • The Exit of the Program.

Below is the Implementation:

# Import the OrderedDict from collections using the import keyword.
from collections import OrderedDict

# Take a dictionary using OrderedDict() (Ordered Dictionary).
orderedDictionary = OrderedDict()
# Give some random keys and values for this dictionary.
orderedDictionary['hello'] = 100
orderedDictionary['this'] = 400
orderedDictionary['is'] = 500
orderedDictionary['Python-Programs'] = 900
# Print the Dictionary before Deleting the key.
print('The given Dictionary Before Deletion : ')
for key, value in orderedDictionary.items():
    print(key, "->", value)
# Remove Some Random Key from the above dictionary using the pop() method.
orderedDictionary.pop('is')
# Print the Dictionary after Deleting the key.
print('The given Dictionary After Deletion : ')
for key, value in orderedDictionary.items():
    print(key, "->", value)
# Insert the same key again to the Ordered Dictionary
orderedDictionary['is'] = 500
# Print the Dictionary after Reinserting the same key.
print('The given Dictionary After Reinserting the same key : ')
for key, value in orderedDictionary.items():
    print(key, "->", value)

Output:

The given Dictionary Before Deletion : 
hello -> 100
this -> 400
is -> 500
Python-Programs -> 900
The given Dictionary After Deletion : 
hello -> 100
this -> 400
Python-Programs -> 900
The given Dictionary After Reinserting the same key : 
hello -> 100
this -> 400
Python-Programs -> 900
is -> 500

Python collections OrderedDict() Method with Examples Read More »

Python Program for Brick Sort Algorithm

Brick Sort Algorithm:

Brick Sort, commonly known as OddEven Sort, is a variant of Bubblesort. The sorting algorithm is separated into two stages: odd and even. The control loops until the array is sorted, ensuring that the even and odd stages are completed in each iteration.

You may be wondering what these odd and even stages represent. We will only sort the elements existing at the odd indexes when the control executes the odd phase. Similarly, during the event phase execution, the control will only sort the elements at the even indexes.

Examples:

Example1:

Input:

Given List = [12, 9, 20, 2, 1, 5, -4]

Output:

The given list after sorting =  [-4, 1, 2, 5, 9, 12, 20]

Example2:

Input:

Given List = [4, -12, 56, 125, 0, -3, 7]

Output:

The given list after sorting = [-12, -3, 0, 4, 7, 56, 125]

Program for Brick Sort Algorithm in Python

 

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

Approach:

  • Give the list as static input and store it in a variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Take a variable say sortng and initialize its value with zero.
  • Loop until the above variable is equal to zero using the while loop.
  • Inside the while loop, make the above sortng variable as 1.
  • Loop from 1 to the list length-1 with the step size of 2 using the for loop. It is for sorting the Odd entries.
  • Inside the loop, check if the iterator value of the given list is greater than the [iterator+1] value using the if conditional statement.
  • If it is true, then swap both the values.
  • Again assign 0 to the sortng variable.
  • Loop from 0 to the list length-1 with the step size of 2 using the for loop. It is for sorting the Even entries.
  • Inside the loop, check if the iterator value of the given list is greater than the [iterator+1] value using the if conditional statement.
  • If it is true, then swap both the values.
  • Make again the sortng variable as 0.
  • Print the given list after sorting.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [12, 9, 20, 2, 1, 5, -4]
# Calculate the length of the given list using the len() function and
# store it in another variable.
lst_len = len(gvn_lst)
# Take a variable and initialize its value with zero.
sortng = 0
# Loop until the above variable is equal to zero using the while loop.
while sortng == 0:
    # Inside the while loop, make the above sortng variable as 1.
    sortng = 1
    # Loop from 1 to the list length-1 with the step size of 2 using the for loop.
    # It is for sorting the Odd entries.
    for itr in range(1, lst_len-1, 2):
        # Inside the loop, check if the iterator value of the given list is
        # greater than the [iterator+1] value using the if conditional statement.
        if gvn_lst[itr] > gvn_lst[itr+1]:
                        # If it is true, then swap both the values.
            gvn_lst[itr], gvn_lst[itr+1] = gvn_lst[itr+1], gvn_lst[itr]
            # Again assign 0 to the sortng variable.
            sortng = 0
    # Loop from 0 to the list length-1 with the step size of 2 using the for loop.
        # It is for sorting the Even entries.
    for itr in range(0, lst_len-1, 2):
        # Inside the loop, check if the iterator value of the given list is greater
                # than the [iterator+1] value using the if conditional statement.
        if gvn_lst[itr] > gvn_lst[itr+1]:
            # If it is true, then swap both the values.
            gvn_lst[itr], gvn_lst[itr+1] = gvn_lst[itr+1], gvn_lst[itr]
            # Make again the sortng variable as 0.
            sortng = 0
# Print the given list after sorting.
print("The given list after sorting = ", gvn_lst)

Output:

The given list after sorting =  [-4, 1, 2, 5, 9, 12, 20]

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Take a variable say sortng and initialize its value with zero.
  • Loop until the above variable is equal to zero using the while loop.
  • Inside the while loop, make the above sortng variable as 1.
  • Loop from 1 to the list length-1 with the step size of 2 using the for loop. It is for sorting the Odd entries.
  • Inside the loop, check if the iterator value of the given list is greater than the [iterator+1] value using the if conditional statement.
  • If it is true, then swap both the values.
  • Again assign 0 to the sortng variable.
  • Loop from 0 to the list length-1 with the step size of 2 using the for loop. It is for sorting the Even entries.
  • Inside the loop, check if the iterator value of the given list is greater than the [iterator+1] value using the if conditional statement.
  • If it is true, then swap both the values.
  • Make again the sortng variable as 0.
  • Print the given list after sorting.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Calculate the length of the given list using the len() function and
# store it in another variable.
lst_len = len(gvn_lst)
# Take a variable and initialize its value with zero.
sortng = 0
# Loop until the above variable is equal to zero using the while loop.
while sortng == 0:
    # Inside the while loop, make the above sortng variable as 1.
    sortng = 1
    # Loop from 1 to the list length-1 with the step size of 2 using the for loop.
    # It is for sorting the Odd entries.
    for itr in range(1, lst_len-1, 2):
        # Inside the loop, check if the iterator value of the given list is
        # greater than the [iterator+1] value using the if conditional statement.
        if gvn_lst[itr] > gvn_lst[itr+1]:
                        # If it is true, then swap both the values.
            gvn_lst[itr], gvn_lst[itr+1] = gvn_lst[itr+1], gvn_lst[itr]
            # Again assign 0 to the sortng variable.
            sortng = 0
    # Loop from 0 to the list length-1 with the step size of 2 using the for loop.
        # It is for sorting the Even entries.
    for itr in range(0, lst_len-1, 2):
        # Inside the loop, check if the iterator value of the given list is greater
                # than the [iterator+1] value using the if conditional statement.
        if gvn_lst[itr] > gvn_lst[itr+1]:
            # If it is true, then swap both the values.
            gvn_lst[itr], gvn_lst[itr+1] = gvn_lst[itr+1], gvn_lst[itr]
            # Make again the sortng variable as 0.
            sortng = 0
# Print the given list after sorting.
print("The given list after sorting = ", gvn_lst)

Output:

Enter some random List Elements separated by spaces = 4 -12 56 125 0 -3 7
The given list after sorting = [-12, -3, 0, 4, 7, 56, 125]

Python Program for Brick Sort Algorithm Read More »

Python Program for Stooge Sort

Stooge Sort:

Stooge sort is a recursive sorting method with high time complexity. The algorithm’s execution time is longer than that of the Bubble sort. It is, though, more efficient than slow sorting.

Algorithm:

  • If the value in the first place is greater than the value in the last position, swap them.
  • If the list contains three or more elements, then
  1. To begin, Stooge sorts the first two-thirds of the list.
  2. Second, Stooge sorts the final two-thirds of the list.
  3. Finally, Stooge sorts the first two-thirds of the list once more.

Steps:

The array is first given to the function, which compares the first and last elements and swaps them if the first element is smaller.

Next, we assess the array’s size; if the size is greater than two, the array’s sections are called recursively to sort the first, last, and first two-thirds(2/3) of the array.

Finally, simply show the sorted array on the window.

Examples:

Example1:

Input:

Given List = [80, 90, 20, -10, 36]

Output:

The given list after sorting =  [-10, 20, 36, 80, 90]

Example2:

Input:

Given List = [56, 43, -3, 100, 13]

Output:

The given list after sorting = [-3, 13, 43, 56, 100]

Program for Stooge Sort in Python

 

Method #1: Using Recursion (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Take a variable and initialize it with the start value as 0.
  • Take another variable and initialize it with the end value as the length of the list-1.
  • Create a Recursive function say Stooge_Sorting() which accepts the given list, start value and end value as the arguments and returns the sorted list.
  • Inside the function, check whether the list has any elements using the if conditional statement.
  • If it is true then return.
  • Check whether the element present at the start value of the list is greater than the element present at the end value using the if conditional statement.
  • If it is true, then swap both of them.
  • Check whether there are more than two elements using the if conditional statement.
  • If it is true, then pass the (gvn_lst, strt_val, (end_val-tempry)) as the arguments to the function itself (Recursive Logic).
  • Pass the (gvn_lst, strt_val+tempry, (end_val)) as the arguments to the function itself (Recursive Logic).
  • Pass the (gvn_lst, strt_val, (end_val-tempry)) as the arguments to the function itself (Recursive Logic).
  • Pass the given list, start value, and end value as the arguments to the Stooge_Sorting() function.
  • Print the given list after sorting.
  • The Exit of the Program.

Below is the implementation:

# Create a Recursive function say Stooge_Sorting() which accepts the given list,
# start value and end value as the arguments and returns the sorted list.


def Stooge_Sorting(gvn_lst, strt_val, end_val):
    # Inside the function, check whether the list has any elements using the if
        # conditional statement.
    if strt_val >= end_val:
        # If it is true then return.
        return
    # Check whether the element present at the start value of the list is greater
        # than the element present at the end value using the if conditional statement.
    if gvn_lst[strt_val] > gvn_lst[end_val]:
        # If it is true, then swap both of them.
        gvn_lst[strt_val], gvn_lst[end_val] = gvn_lst[end_val], gvn_lst[strt_val]
        # Check whether there are more than two elements using the if conditional
    # statement.
    if end_val-strt_val+1 > 2:
        tempry = (int)((end_val-strt_val+1)/3)
        # If it is true, then pass the (gvn_lst, strt_val, (end_val-tempry)) as the
        # arguments to the function itself (Recursive Logic).
        Stooge_Sorting(gvn_lst, strt_val, (end_val-tempry))
        # Pass the (gvn_lst, strt_val+tempry, (end_val)) as the arguments to the
        # function itself (Recursive Logic).
        Stooge_Sorting(gvn_lst, strt_val+tempry, (end_val))
        # Pass the (gvn_lst, strt_val, (end_val-tempry)) as the
        # arguments to the function itself (Recursive Logic).
        Stooge_Sorting(gvn_lst, strt_val, (end_val-tempry))


# Give the list as static input and store it in a variable.
gvn_lst = [80, 90, 20, -10, 36]
# Calculate the length of the given list using the len() function and store
# it in another variable.
lst_len = len(gvn_lst)
# Take a variable and initialize it with the start value as 0.
strt_val = 0
# Take another variable and initialize it with the end value as length of the
# list-1.
end_val = lst_len-1
# Pass the given list, start value, and end value as the arguments to the
# Stooge_Sorting() function.
Stooge_Sorting(gvn_lst, strt_val, end_val)
# Print the given list after sorting.
print("The given list after sorting = ", gvn_lst)

Output:

The given list after sorting =  [-10, 20, 36, 80, 90]

Method #2: Using Recursion (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Take a variable and initialize it with the start value as 0.
  • Take another variable and initialize it with the end value as the length of the list-1.
  • Create a Recursive function say Stooge_Sorting() which accepts the given list, start value and end value as the arguments and returns the sorted list.
  • Inside the function, check whether the list has any elements using the if conditional statement.
  • If it is true then return.
  • Check whether the element present at the start value of the list is greater than the element present at the end value using the if conditional statement.
  • If it is true, then swap both of them.
  • Check whether there are more than two elements using the if conditional statement.
  • If it is true, then pass the (gvn_lst, strt_val, (end_val-tempry)) as the arguments to the function itself (Recursive Logic).
  • Pass the (gvn_lst, strt_val+tempry, (end_val)) as the arguments to the function itself (Recursive Logic).
  • Pass the (gvn_lst, strt_val, (end_val-tempry)) as the arguments to the function itself (Recursive Logic).
  • Pass the given list, start value, and end value as the arguments to the Stooge_Sorting() function.
  • Print the given list after sorting.
  • The Exit of the Program.

Below is the implementation:

# Create a Recursive function say Stooge_Sorting() which accepts the given list,
# start value and end value as the arguments and returns the sorted list.


def Stooge_Sorting(gvn_lst, strt_val, end_val):
    # Inside the function, check whether the list has any elements using the if
        # conditional statement.
    if strt_val >= end_val:
        # If it is true then return.
        return
    # Check whether the element present at the start value of the list is greater
        # than the element present at the end value using the if conditional statement.
    if gvn_lst[strt_val] > gvn_lst[end_val]:
        # If it is true, then swap both of them.
        gvn_lst[strt_val], gvn_lst[end_val] = gvn_lst[end_val], gvn_lst[strt_val]
        # Check whether there are more than two elements using the if conditional
    # statement.
    if end_val-strt_val+1 > 2:
        tempry = (int)((end_val-strt_val+1)/3)
        # If it is true, then pass the (gvn_lst, strt_val, (end_val-tempry)) as the
        # arguments to the function itself (Recursive Logic).
        Stooge_Sorting(gvn_lst, strt_val, (end_val-tempry))
        # Pass the (gvn_lst, strt_val+tempry, (end_val)) as the arguments to the
        # function itself (Recursive Logic).
        Stooge_Sorting(gvn_lst, strt_val+tempry, (end_val))
        # Pass the (gvn_lst, strt_val, (end_val-tempry)) as the
        # arguments to the function itself (Recursive Logic).
        Stooge_Sorting(gvn_lst, strt_val, (end_val-tempry))


# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
   
# Calculate the length of the given list using the len() function and store
# it in another variable.
lst_len = len(gvn_lst)
# Take a variable and initialize it with the start value as 0.
strt_val = 0
# Take another variable and initialize it with the end value as length of the
# list-1.
end_val = lst_len-1
# Pass the given list, start value, and end value as the arguments to the
# Stooge_Sorting() function.
Stooge_Sorting(gvn_lst, strt_val, end_val)
# Print the given list after sorting.
print("The given list after sorting = ", gvn_lst)

Output:

Enter some random List Elements separated by spaces = 56 43 -3 100 13
The given list after sorting = [-3, 13, 43, 56, 100]

 

Python Program for Stooge Sort Read More »