Author name: Vikram Chiluka

Patchify in Python – To Extract Patches from Large Images

In this article, we’ll look at how to extract patches from large pictures using Python.

We prefer to train any deep learning algorithm with tiny images since they generate better results. But what if we have very large images? One possibility is to break the larger photographs into smaller patches, which would allow us to train any algorithm.

You’re probably wondering what patch means. An image patch, as the name implies, is a collection of pixels in a photograph. Let’s say I have a 20 by 20-pixel image. It can be broken into 1000 2 *2 pixel square patches.

Patchify in Python:

patchify is a Python tool for cropping pictures and saving the cropped or patched images in a Numpy array.

Patchify can break an image into small overlapping pieces based on the patch unit size supplied, and then fuse the areas back together with the original image.

The patchify module is used to transform photos to image patches, whereas Numpy is used to build image data.

But first, use the pip command to ensure that patchify is installed on your system.

pip install patchify

Output:

Collecting patchify Downloading patchify-0.2.3-py3-none-any.whl (6.6 kB)
Requirement already satisfied: numpy<2,>=1 in /usr/local/lib/python3.7/
dist-packages (from patchify) (1.19.5) Installing collected packages: 
patchify Successfully installed patchify-0.2.3

Patchify in Python – To Extract Patches from Large Images

 

Method #1: Using patchify Module(Static Input)

Approach:

  • Import the numpy library as np using the import keyword.
  • Import patchify function from patchify module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Create an array using the np.array() method for creating the image data by passing the given list as an argument and store it in another variable.
  • Print the shape of the image data obtained using the shape method.
  • Pass the above image, pixel size, step value as the arguments to the patchify() function for extracting the patches from the above image.
  • Store it in another variable.
  • Print all the patches of the image using the shape method.
  • The Exit of the Program.

Below is the implementation:

# Import the numpy library as np using the import keyword.
import numpy as np
# Import patchify function from patchify module using the import keyword.
from patchify import patchify
# Give the list as static input and store it in a variable.
gvn_list = [[35, 45, 55, 65], [20, 25, 75, 45],
            [100, 15, 12, 90], [200, 300, 400, 10], [12, 40, 50, 60]]
# Create an array using the np.array() method for creating the image data
# by passing the given list as an argument.
# store it in another variable.
rslt_img = np.array(gvn_list)
# Print the shape of the image data obtained using the shape method.
print(rslt_img.shape)
# Pass the above image, pixel size, step value as the arguments to the patchify() function
# for extracting the patches from the above image.
# Store it in another variable.
rsltpatchs = patchify(rslt_img, (2, 2), step=2)
# Print all the patches of the image using the shape method.
print(rsltpatchs.shape)

Output:

(5, 4)
(2, 2, 2, 2)

 

 

Patchify in Python – To Extract Patches from Large Images Read More »

Python Program for Calculating Variance

Variance:

In statistics, variance is a key mathematical tool. It is used to handle enormous amounts of data. It is the square of the standard deviation for a given data set.

Variance is also known as the second central moment of a distribution. It is calculated using the mean of the square minus the square of the mean of a particular data set.

Let us calculate the variance by the following methods. They are

  1. Using Rudimentary Method.
  2. Using Statistics Module

Using Rudimentary Method:

This is the most fundamental method for calculating the variance of lists. In this, we use the mathematical formula to compute the mean and then the variance.

Here, We are not utilizing any of the built-in techniques here, but rather manually computing the variance of lists by writing out the formula.

Using Statistics Module:

Python statistics.variance() Method with Examples

Examples:

Example1:

Input:

Given List = [10, 11, 12, 13, 14]

Output:

The Given list's Variance =  2.0

Example2:

Input:

Given List = [12, 6, 5, 2, 1]

Output:

The Given list's Variance = 14.959999999999999

Program for Calculating Variance in Python

 

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

Using Rudimentary Method:

Approach:

  • Give the list as static input and store it in a variable.
  • Calculate the sum of all the elements of the given list using the sum() function and store it in a variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Divide the above-obtained list sum by the length of the given list to get the mean of the list items.
  • Store it in another variable.
  • Calculate the variance of the given list using the mathematical formula and list comprehension.
  • Store it in another variable.
  • Print the variance of the 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 = [10, 11, 12, 13, 14]
# Calculate the sum of all the elements of the given list using the sum()
# function and store it in a variable.
lst_sum = sum(gvn_lst)
# Calculate the length of the given list using the len() function and store it in
# another variable.
lst_len = len(gvn_lst)
# Divide the above-obtained list sum by the length of the given list to get
# the mean of the list items.
# Store it in another variable.
rslt_mean = lst_sum / lst_len
# Calculate the variance of the given list using the mathematical formula and
# list comprehension.
# Store it in another variable.
rslt_varince = sum((a - rslt_mean) ** 2 for a in gvn_lst) / lst_len
# Print the variance of the given list.
print("The Given list's Variance = ", rslt_varince)

Output:

The Given list's Variance =  2.0

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

Using Rudimentary Method:

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the sum of all the elements of the given list using the sum() function and store it in a variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Divide the above-obtained list sum by the length of the given list to get the mean of the list items.
  • Store it in another variable.
  • Calculate the variance of the given list using the mathematical formula and list comprehension.
  • Store it in another variable.
  • Print the variance of the 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(float, input(
   'Enter some random List Elements separated by spaces = ').split()))
   
# Calculate the sum of all the elements of the given list using the sum()
# function and store it in a variable.
lst_sum = sum(gvn_lst)
# Calculate the length of the given list using the len() function and store it in
# another variable.
lst_len = len(gvn_lst)
# Divide the above-obtained list sum by the length of the given list to get
# the mean of the list items.
# Store it in another variable.
rslt_mean = lst_sum / lst_len
# Calculate the variance of the given list using the mathematical formula and
# list comprehension.
# Store it in another variable.
rslt_varince = sum((a - rslt_mean) ** 2 for a in gvn_lst) / lst_len
# Print the variance of the given list.
print("The Given list's Variance = ", rslt_varince)

Output:

Enter some random List Elements separated by spaces = 12 6 5 2 1
The Given list's Variance = 14.959999999999999

 

Python Program for Calculating Variance Read More »

Python Program for Numpy average() Function

Those people with a statistical background are highly familiar with the phrase “average.” Data Science and AI practitioners, whether deliberately or unknowingly, use this word in preprocessing procedures.

Numpy average() Function:

In general statistics, the average is defined as the sum of all numbers divided by the sum of their totals. The major purpose of this effort is to assist us to grasp the fundamental value contained inside the dataset.

For Example: 

Let us consider the marks obtained by the 5 students out of 100.

s1 = 80,

s2 = 95

s3 = 35

s4 = 65

s5 = 70

The average of their marks = (80+95+35+65+70)/5 = 345/5 = 69.

Formula:

Average = sum of all Frequencies/ No. of Frequencies

Where Frequencies = values given in the dataset

We learned about the key benefit from the preceding example. The best value is required for the calculation of many parameters. In the actual world, the mean can be used in a variety of contexts.

  • Predicting a state’s average income.
  • Choosing the best market selling price for the items.
  • Normalization of test scores entails calculating the mean.

The values vary greatly, and there are several variations of this term:

Arithmetic mean: In statistics, it is used to examine tabular data.
Regular mean/average: This is a term that is commonly used in common mathematical operations.

We shall now use the second form.

Examples:

Example1:

Input:

Given List = [20, 30, 50, 10, 70]

Output:

The Average of all the list items = 36.0

Example2:

Input:

Given Array = [[10, 8, 4],[4, 15, 65], [7, 16, 2]]

Output:

The given Array average = 14.555555555555555

Program for Numpy average() Function 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 sum of all the elements of the given list using the sum() function and store it in a variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Divide the above-obtained list sum by the length of the given list to get the average of the list items.
  • Store it in another variable.
  • Print the average of all the list items.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [20, 30, 50, 10, 70]
# Calculate the sum of all the elements of the given list using the sum()
# function and store it in a variable.
lst_sum = sum(gvn_lst)
# Calculate the length of the given list using the len() function and
# store it in another variable.
lst_len = len(gvn_lst)
# Divide the above-obtained list sum by the length of the given list to get the
# average of the list items.
# Store it in another variable.
avrge = lst_sum/lst_len
# Print the average of all the list items.
print("The Average of all the list items = ", avrge)

Output:

The Average of all the list items =  36.0

Using Numpy Library:

The average() function in the Numpy module simplifies our task. We are all aware that this API is one of the most well-known libraries for array operations. Several built-in techniques help to minimize our code and make some things easier to implement. It has the NumPy ndarray type.

Approach:

  • Import the numpy library as np using the import keyword.
  • Give the list as static input and store it in a variable.
  • Create an array using the np.array() method by passing the given list as an argument and store it in another variable.
  • Calculate the average of the above array using the np.average()  method and store it in another variable.
  • Print the average of the given array.
  • The Exit of the Program.

Below is the implementation:

# Import the numpy library as np using the import function.
import numpy as np
# Give the list as static input and store it in a variable.
gvn_lst = [22, 12, 3, -1, -3, 98]
# Create an array using the np.array() method by passing the given list as an
# argument and store it in another variable.
rslt_arry = np.array(gvn_lst)
# Calculate the average of the above array using the np.average()  method and
# store it in another variable.
averg = np.average(rslt_arry)
# Print the average of the given array.
print("The given Array average =  ", averg)

Output:

The given Array average = 7.0

For 3 -Dimensional Array

# Import the numpy library as np using the import function.
import numpy as np
# Give the 3-Dimensional list as static input and store it in a variable.
gvn_list = [[10, 8, 4],[4, 15, 65], [7, 16, 2]]
# Create an array using the np.array() method by passing the given list as an
# argument and store it in another variable.
rslt_arry = np.array(gvn_list)
# Calculate the average of the above array using the np.average()  method and
# store it in another variable.
averg = np.average(rslt_arry)
# Print the average of the given array.
print("The given Array average =  ", averg)

Output:

The given Array average = 14.555555555555555

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 sum of all the elements of the given list using the sum() function and store it in a variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Divide the above-obtained list sum by the length of the given list to get the average of the list items.
  • Store it in another variable.
  • Print the average of all the list items.
  • 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(float, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Calculate the sum of all the elements of the given list using the sum()
# function and store it in a variable.
lst_sum = sum(gvn_lst)
# Calculate the length of the given list using the len() function and
# store it in another variable.
lst_len = len(gvn_lst)
# Divide the above-obtained list sum by the length of the given list to get the
# average of the list items.
# Store it in another variable.
avrge = lst_sum/lst_len
# Print the average of all the list items.
print("The Average of all the list items = ", avrge)

Output:

Enter some random List Elements separated by spaces = 32 50 15 44 65
The Average of all the list items = 41.2

Using Numpy Library:

Approach:

  • Import the numpy library as np using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Create an array using the np.array() method by passing the given list as an argument and store it in another variable.
  • Calculate the average of the above array using the np.average()  method and store it in another variable.
  • Print the average of the given array.
  • The Exit of the Program.

Below is the implementation:

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

# Create an array using the np.array() method by passing the given list as an
# argument and store it in another variable.
rslt_arry = np.array(gvn_lst)
# Calculate the average of the above array using the np.average()  method and
# store it in another variable.
averg = np.average(rslt_arry)
# Print the average of the given array.
print("The given Array average =  ", averg)

Output:

Enter some random List Elements separated by spaces = 32.5 47 85.3 100 50
The given Array average = 62.96

Python Program for Numpy average() Function Read More »

Python NLTK Program to Implement N-Grams

Natural language processing and text mining both make extensive use of text n-grams. It’s basically a string of words that all appear in the same window at the same time.

When computing n-grams, you usually advance one word at a time (although in more complex scenarios you can move n-words). N-grams can be used for a variety of things.

N = 1: Welcome to Python Programs

The Unigrams of this sentence is:  welcome, to, Python, Programs

N = 2: Welcome to Python Programs

bigrams:

Welcome to,

to Python

Python Programs

N=3: trigrams: Welcome to Python, to Python Programs

For example, when developing language models, n-grams are used to generate not only unigram models but also bigrams and trigrams.

Examples:

Example1:

Input:

Given String = "Hello Welcome to Python Programs"
Given n value = 2

Output:

('Hello', 'Welcome')
('Welcome', 'to')
('to', 'Python') 
('Python', 'Programs')

Example2:

Input:

Given String = "good morning all this is python programs"
Given n value = 3

Output:

('good', 'morning', 'all')
('morning', 'all', 'this')
('all', 'this', 'is') 
('this', 'is', 'python')
('is', 'python', 'programs')

NLTK Program to Implement N-Grams

 

Method #1: Using NLTK Module (Static Input)

Approach:

  • Import ngrams from the nltk module using the import keyword.
  • Give the string as static input and store it in a variable.
  • Give the n value as static input and store it in another variable.
  • Split the given string into a list of words using the split() function.
  • Pass the above split list and the given n value as the arguments to the ngrams() function and store it in another variable.
  • Loop in the above result obtained using the for loop.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Import ngrams from the nltk module using the import keyword
from nltk import ngrams
# Give the string as static input and store it in a variable.
gvn_str = "Hello Welcome to Python Programs"
# Give the n value as static input and store it in another variable.
gvn_n_val = 2
# Split the given string into list of words using the split() function
splt_lst = gvn_str.split()
# Pass the above split list and the given n value as the arguments to the ngrams()
# function and store it in another variable.
rslt_n_grms = ngrams(splt_lst, gvn_n_val)
# Loop in the above result obtained using the for loop
for itr in rslt_n_grms:
    # Inside the loop, print the iterator value.
    print(itr)

Output:

('Hello', 'Welcome')
('Welcome', 'to')
('to', 'Python') 
('Python', 'Programs')

Method #2: Using NLTK Module (User Input)

Approach:

  • Import ngrams from the nltk module using the import keyword.
  • Give the string as user input using the input() function and store it in a variable.
  • Give the n value as user input using the int(input()) function and store it in another variable.
  • Split the given string into a list of words using the split() function.
  • Pass the above split list and the given n value as the arguments to the ngrams() function and store it in another variable.
  • Loop in the above result obtained using the for loop.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Import ngrams from the nltk module using the import keyword
from nltk import ngrams
# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Give the n value as user input using the int(input()) function and store it in another variable.
gvn_n_val = int(input("Enter some random number(n) = "))
# Split the given string into list of words using the split() function
splt_lst = gvn_str.split()
# Pass the above split list and the given n value as the arguments to the ngrams()
# function and store it in another variable.
rslt_n_grms = ngrams(splt_lst, gvn_n_val)
# Loop in the above result obtained using the for loop
for itr in rslt_n_grms:
    # Inside the loop, print the iterator value.
    print(itr)

Output:

Enter some random string = good morning all this is python programs 
Enter some random number(n) = 3 
('good', 'morning', 'all')
('morning', 'all', 'this')
('all', 'this', 'is')
('this', 'is', 'python') 
('is', 'python', 'programs')

 

 

 

Python NLTK Program to Implement N-Grams Read More »

Python Program to Generate Random Quotes from quote Module

How to Generate a keyword at random?

To get quotes from different backgrounds, we will generate a random keyword each time, and the program will return a quote from a specific author centered on the keyword.

We use the random_word module to get any random English word. The random_word module can produce a single random word or a list of random words.

Before going to the code, install the random_word module as shown below

pip install random_word

Output:

Collecting random_word Downloading Random_Word-1.0.7-py3-none-any.whl (8.0 kB)
 Requirement already satisfied: requests in /usr/local/lib/python3.7/
dist-packages (from random_word) (2.23.0) Collecting nose Downloading 
nose-1.3.7-py3-none-any.whl (154 kB) |████████████████████████████████| 
154 kB 8.6 MB/s 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->
random_word) (1.24.3) Requirement already satisfied: idna<3,>=2.5 in /usr/
local/lib/python3.7/dist-packages (from requests->random_word) (2.10) 
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/
dist-packages (from requests->random_word) (2021.10.8) Requirement already
 satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages 
(from requests->random_word) (3.0.4) Installing collected packages: nose, 
random-word Successfully installed nose-1.3.7 random-word-1.0.7
pip install quote

Output:

Collecting quote Downloading quote-2.0.4.tar.gz (4.1 kB) Collecting gazpacho>=1.0
Downloading gazpacho-1.1.tar.gz (7.9 kB) Installing build dependencies ... done
Getting requirements to build wheel ... done Preparing wheel metadata ... done
Building wheels for collected packages: quote, gazpacho Building wheel for quote
(setup.py) ... done Created wheel for quote: filename=quote-2.0.4-py3-none-any.
whl size=5005 sha256=2afb78d9fe4304db45fa2462ec1e37f927bf09c39485859da3b0bb3f6b
7be7bc Stored in directory: /root/.cache/pip/wheels/74/8c/7d/2670c2479ed9ff454b
92c11a0459b9f8dcbc461ede57f8a493 Building wheel for gazpacho (PEP 517) ... done
Created wheel for gazpacho: filename=gazpacho-1.1-py3-none-any.whl size=7483
sha256=0dd0461047f3c9b88afa32b3c0411b2a29a503006323d10d30c45544683637f6 Stored
in directory: /root/.cache/pip/wheels/db/6b/a2/486f272d5e523b56bd19817c14ef35e
c1850644dea78f9dd76 Successfully built quote gazpacho Installing collected 
packages: gazpacho, quote Successfully installed gazpacho-1.1 quote-2.0.4

Program to Generate Random Quotes from quote Module in Python

Method #1: Using random_word Module (Static Input)

Approach:

  • Import RandomWords from the random_word module using the import keyword.
  • Import quote from the quote module using the import keyword.
  • Create an object for the RandomWords() to extract the words and store it in a variable.
  • Apply the get_random_word() function on the above object to get a random word and store it in another variable.
  • Print the above word obtained.
  • Pass the above word obtained and limit = 1 as the arguments to the quote() function to generate a quote at random. Set a limit to limit the number of quotes generated.
  • Store it in another variable.
  • The quote function provides a collection of dictionaries, each containing information about a certain quote.
  • Loop till the length of the above result dictionary using the for loop.
  • Inside the loop, print the corresponding quote.
  • The Exit of the Program.

Below is the implementation:

# Import RandomWords from the random_word module using the import keyword
from random_word import RandomWords
# Import quote from the quote module using the import keyword
from quote import quote
# Create an object for the RandomWords() to extract the words and store it in
# a variable.
randobj = RandomWords()
# Apply the get_random_word() function on the above object to get a random word
# and store it in another variable.
wrd = randobj.get_random_word()
# Print the above word obtained.
print("The result Keyword obtained = ", wrd)
# Pass the above word obtained and limit = 1 as the arguments to the quote()
# function to generate a quote at random.
# Set a limit to limit the number of quotes generated.
# Store it in another variable.
# The quote function provides a collection of dictionaries, each containing
# information about a certain quote.
rslt = quote(wrd, limit=1)
# Loop till the length of the above result dictionary using the for loop.
for itr in range(len(rslt)):
    # Print the corresponding quote.
    print("The result Quote obtained = ", rslt[itr]['quote'])

Output:

The result Keyword obtained = yeoman
The result Quote obtained = The scene I had just witnessed (a couple making love in the ocean) brought back a lot of memories – not of things I had done but of things I had failed to do, wasted hours and frustrated moments and opportunities forever lost because time had eaten so much of my life and I would never get it back. I envied Yeoman and felt sorry for myself at the same time, because I had seen him in a moment that made all my happiness seem dull.

 

 

 

Python Program to Generate Random Quotes from quote Module Read More »

Programming Languages: Python vs Scala

Python and Scala are the two most popular programming languages for data science, big data, and cluster computing.

Python is a high-level object-oriented programming language that is interpreted. It is a language that is dynamically typed. It supports multiple programming models, including object-oriented, imperative, functional, and procedural paradigms, and has an interface to many OS system calls.

Scala is an object-oriented programming language as well. It is used to provide functional programming support as well as a strong static type system. Scala derives its name from a combination of ‘scalable’ and ‘language,’ as it can scale according to the number of users, and everything is an expression here. It seamlessly combines the features of object-oriented and functional programming languages.

Python vs Scala:
                        Python                         Scala
Python is a language that uses dynamic typing.Scala is a language that uses static typing.

 

Python, as a dynamically typed language, generates additional work for the interpreter at runtime. During runtime, it must decide on the data types.Scala is a statically typed language that uses the JVM, making it 10 times faster than Python. As a result, when dealing with large amounts of data, Scala should be considered instead of Python.
Python is simple to learn and apply. Its popularity originated from its English-like syntax. Python makes it simple for developers to write code.Scala is easier to learn than Python. Scala, on the other hand, plays a much larger and more important role than Python in concurrent and scalable systems.
It determines the data types at runtime.This is not the case in Scala, which is why it should be used instead of Python when dealing with large amounts of data.
In comparison to Scala, the Python community is much larger.Both are open source, and Scala has a strong community behind it. However, it is lesser than Python.
Python’s testing process and methodologies are much more complex because it is a dynamic programming language.Scala is a statically typed language, so testing is much easier.

 

Python has an interface to many OS system calls and libraries. There are numerous interpreters available.It is essentially a compiled language, with all source code being compiled prior to execution.
Python includes libraries for machine learning, data science, and natural language processing (NLP).Scala, on the other hand, lacks such tools.

 

 

When there is a change to the existing code, the Python language is highly prone to bugs.Scala is a statically typed language with an interface for detecting compile-time errors. As a result, refactoring code in Scala is much easier and more ideal than in Python.
Python Programming Language Advantages
  • Simple to learn and comprehend
  • Python is preferred by a large number of developers over many other programming languages.
  • It includes a large number of libraries, modules, and functions.
  • It also includes a wide range of built-in functions, data types, and modules.
  • It is quick and one of the best languages for beginners to get started with.
Python Programming Language Drawbacks
  • Python is a dynamically typed language that consumes slightly more computer time than C, C++, or Java.
  • The Python programming language consumes a lot of memory in addition to a lot of time.
Scala Benefits
  • Access to JVM libraries for Java support
  • It shares several readable syntax features with other popular languages like Ruby and Java.
Scala Disadvantages
  • Because it is both object-oriented and functional programming language, the code language of the programming language can become complex.
  • Scala is a programming language used by a small number of developers to create applications and models.

 

 

Programming Languages: Python vs Scala Read More »

Python Program for Quartile Deviation

Quartile Deviation

The quartile deviation is the absolute measure of dispersion. It is computed by dividing the difference between the top and bottom quartiles in half.

The quartile deviation is the absolute measure of dispersion, where dispersion is the amount by which the values in the distribution differ from the mean value.

Even if there is only one exceptionally high or low value in the data, the range’s utility as a measure of dispersion is reduced or diminished.

To calculate the quartile deviation, we must divide the data into four portions, each of which has 25% of the values.

The quartile deviation of the data is computed by dividing the difference between the top (75%) and bottom (25%) quartiles by half.

Implementation:

Let’s look at how to use Python to calculate a dataset’s quartile deviation.

To compute it in Python, first, create a dataset, then find the quartile1, quartile2, and quartile3 from the data, and last create a function that returns the product of half the difference between quartile3 and quartile1.

Program for Quartile Deviation in Python

Method #1: Using numpy Library (Static Input)

Approach:

  • Import the numpy library as np using the import function.
  • Pass the lower limit, upper limit, and step size with some random numbers to the range() function and convert it into a list using the list() function. It is considered as the dataset.
  • Store it in a variable.
  • Pass the above dataset,  0.25  deviation as the arguments to the quantile() function and store it in a variable.
  • Pass the above dataset,  0.50  deviation as the arguments to the quantile() function and store it in another variable.
  • Pass the above dataset,  0.75 deviation as the arguments to the quantile() function and store it in another variable.
  • Print the above three variables i.e, quartile1, quartile1, and quartile1.
  • Create a function say quartile_deviatn() which accepts two numbers as the arguments and returns half of the difference of two numbers.
  • Inside the function, return the value half of the difference of two numbers ((x – y)/2).
  • Pass the quartile3, quartile1 as arguments to the quartile_deviatn() function and store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import the numpy library as np using the import function.
import numpy as np
# Pass the lower limit, upper limit, and step size with some random numbers to the
# range() function and convert it into a list using the list() function.
# It is considered as the dataset.
# Store it in a variable.
gvn_dataset = list(range(70, 200, 10))
# Pass the above dataset,  0.25  deviation as the arguments to the quantile()
# function and store it in a variable.
quartle_1 = np.quantile(gvn_dataset, 0.25)
# Pass the above dataset,  0.50  deviation as the arguments to the quantile()
# function and store it in another variable.
quartle_2 = np.quantile(gvn_dataset, 0.50)
# Pass the above dataset,  0.75 deviation as the arguments to the quantile()
# function and store it in another variable.
quartle_3 = np.quantile(gvn_dataset, 0.75)
# Print the above three variables i.e, quartile1, quartile1, and quartile1.
print("The 1st Quartile =  ", quartle_1)
print("The 2nd Quartile =  ", quartle_2)
print("The 3rd Quartile =  ", quartle_3)
# Create a function say quartile_deviatn() which accepts two numbers as the
# arguments and returns half of the difference of two numbers.


def quartile_deviatn(x, y):
    # Inside the function, return the value half of the difference of two numbers
    # ((x - y)/2).
    return (x - y)/2


# Pass the quartile3, quartile1 as arguments to the quartile_deviatn() function
# and store it in a variable.
rslt = quartile_deviatn(quartle_3, quartle_1)
# Print the above result.
print("The result is = ", rslt)

Output:

The 1st Quartile = 100.0
The 2nd Quartile = 130.0
The 3rd Quartile = 160.0
The result is = 30.0

Method #2: Using numpy Library (User Input)

Approach:

  • Import the numpy library as np using the import function.
  • Give the lower limit as user input using the int(input()) function and store it in a variable.
  • Give the upper limit as user input using the int(input()) function and store it in another variable.
  • Give the step size as user input using the int(input()) function and store it in another variable.
  • Pass the lower limit, upper limit, and step size with some random numbers to the range() function and convert it into a list using the list() function. It is considered as the dataset.
  • Store it in a variable.
  • Pass the above dataset,  0.25  deviation as the arguments to the quantile() function and store it in a variable.
  • Pass the above dataset,  0.50  deviation as the arguments to the quantile() function and store it in another variable.
  • Pass the above dataset,  0.75 deviation as the arguments to the quantile() function and store it in another variable.
  • Print the above three variables i.e, quartile1, quartile1, and quartile1.
  • Create a function say quartile_deviatn() which accepts two numbers as the arguments and returns half of the difference of two numbers.
  • Inside the function, return the value half of the difference of two numbers ((x – y)/2).
  • Pass the quartile3, quartile1 as arguments to the quartile_deviatn() function and store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import the numpy library as np using the import function.
import numpy as np
# Give the lower limit as user input using the int(input()) function and
# store it in a variable.
gvnlwr_lmt = int(input("Enter some random number = "))
# Give the upper limit as user input using the int(input()) function and
# store it in another variable.
gvnupr_lmt = int(input("Enter some random number = "))
# Give the step size as user input using the int(input()) function and
# store it in another variable.
gvn_step = int(input("Enter some random number = "))
# Pass the lower limit, upper limit, and step size with some random numbers to the
# range() function and convert it into a list using the list() function.
# It is considered as the dataset.
# Store it in a variable.
gvn_dataset = list(range(gvnlwr_lmt, gvnupr_lmt, gvn_step))
# Pass the above dataset,  0.25  deviation as the arguments to the quantile()
# function and store it in a variable.
quartle_1 = np.quantile(gvn_dataset, 0.25)
# Pass the above dataset,  0.50  deviation as the arguments to the quantile()
# function and store it in another variable.
quartle_2 = np.quantile(gvn_dataset, 0.50)
# Pass the above dataset,  0.75 deviation as the arguments to the quantile()
# function and store it in another variable.
quartle_3 = np.quantile(gvn_dataset, 0.75)
# Print the above three variables i.e, quartile1, quartile1, and quartile1.
print("The 1st Quartile =  ", quartle_1)
print("The 2nd Quartile =  ", quartle_2)
print("The 3rd Quartile =  ", quartle_3)
# Create a function say quartile_deviatn() which accepts two numbers as the
# arguments and returns half of the difference of two numbers.


def quartile_deviatn(x, y):
    # Inside the function, return the value half of the difference of two numbers
    # ((x - y)/2).
    return (x - y)/2


# Pass the quartile3, quartile1 as arguments to the quartile_deviatn() function
# and store it in a variable.
rslt = quartile_deviatn(quartle_3, quartle_1)
# Print the above result.
print("The result is = ", rslt)

Output:

Enter some random number = 45 
Enter some random number = 90 
Enter some random number = 5 
The 1st Quartile = 55.0 
The 2nd Quartile = 65.0 
The 3rd Quartile = 75.0 
The result is = 10.0

 

Python Program for Quartile Deviation Read More »

Major Differences Between Python2 vs Python3

Python 3 is an improved version of the Python programming language over Python 2. There are numerous noticeable differences or improvements in the Python 3 versions. Some of them are that the syntax in Python 3 is simpler than in Python 2.

Exception arguments in Python 3 are represented by using parenthesis, which was not present in previous versions; print in Python 3 is a function, whereas print in Python 2 is a statement. When two integers were divided in Python 2, the resulting value was also shown as an integer, but Python 3 allows float value results as well, and the range() function is new in Python 3, which was not present in previous versions.

Python3 vs Python2

                                    Python-3                      Python-2
A print is a type of function.In python2, A print is a type of statement.
Strings are stored as Unicode by default

(UTF-8).

Labeled with “u” if stored as Unicode.
If two integers are divided, a float value is returned if necessary.When dividing two integers, always return an integer value.
Syntax becomes more simple and understandable.Compared to python3, the syntax here is a bit difficult.
Variable values in Python 3 never change.When global variables are used within a for-loop in Python 2, their values change.
Python 3 was introduced in the year 2008.Python 2 was introduced in the year 2000.
Exceptions in Python 3 are enclosed in parentheses.Exceptions in Python 2 are denoted by notations.
Ordering comparison rules have been simplified.It is more difficult to understand than Python 3.
To perform iterations, Python 3 introduced the new Range() function.Iterations are handled by the xrange() function in Python 2.
Many libraries are written in Python 3 to be used only with Python 3.Many Python 2 libraries are not fully compatible.
Python 3 does not support backward compatibility with Python 2.Python 2 code can be converted to Python 3 with considerable effort.
Python 3 is used in a variety of fields such as software engineering, data science, and so on.Python 2 was primarily used to train as a DevOps Engineer. It will be phased out by 2020.

Comparing the Print statements

                          Python2: print “hello this is Python-Programs”

                          Python3: print(“hello this is Python-Programs”)

Comparison of the input statements

Python2:

For strings :   raw_input()

For Integers : input()

Python3:  input()we use input for all kinds of input.

Print statement variables

 Python2:   

gvn_str = “welcome to Python-Programs”

print (“Given string =  % ” % gvn_str )

 Python3:

gvn_str = “welcome to Python-Programs”
print (“Given string = {0} “) .format(gvn_str ))

Comparing Error Handling:  In Python3, the programmer must include an extra keyword in the except block.

Python2:   

 try:
//block code
except <ERROR>,err:
//block code

Python3:   

try:
// block code
except <ERROR> as err:
// block code

When it comes to deciding whether to use Python 2 or Python 3, we can safely say that Python 3 is the clear winner. Also, if you are a new programmer, I would recommend Python3.

Major Differences Between Python2 vs Python3 Read More »

Python Program for collections.UserString Function

Python collections.UserString() Function:

Python’s collections module includes a String-like container called UserString. This class serves as a wrapper class for string objects. This class is useful when one wants to create their own string with modified or new functionality. It can be thought of as a method of adding new behaviors to the string. This class takes any string-convertible argument and simulates a string whose content is kept in a regular string. This class’s data attribute provides access to the string.

Syntax:

collections.UserString(sequence)

Program for collections.UserString Function in Python

Method #1: Using collections Module (Static Input)

Approach:

  • Import UserString() function from the collections module using the import keyword.
  • Give the string as static input and store it in a variable.
  • Pass the given string as an argument to the UserString() function to create a user string for the given string.
  • Store it in another variable.
  • Print the above result.
  • Create an empty user string using the UserString() function and store it in another variable.
  • Print the above obtained empty user string.
  • The Exit of the Program.

Below is the implementation:

# Import UserString() function from the collections module using the import keyword.
from collections import UserString
# Give the string as static input and store it in a variable.
gvn_str = 'hello'
# Pass the given string as an argument to the UserString() function to
# create a user string for the given string.
# Store it in another variable.
rsltusr_str = UserString(gvn_str)
# Print the above result.
print("The user string for the given string is :")
print(rsltusr_str.data)
# Create an empty user string using the UserString() function
# and store it in another variable.
print("The empty user string is :")
emty_rsltstr = UserString("")
# Print the above obtained empty user string.
print(emty_rsltstr.data)

Output:

The user string for the given string is :
hello
The empty user string is :

Example2:

Approach:

  • Import UserString() function from the collections module using the import keyword.
  • Create a class by passing the UserString function as an argument.
  • Inside the class, create a function by passing the second string as an argument for appending some random string.
  • Concatenate the second string to the given string using the string concatenation.
  • Create another function by passing the second string as an argument for removing some random string from the given string.
  • Inside the function, remove all the second-string characters by replacing it with a null string using the replace() function.
  • In the main Function,
  • Give the string as static input and store it in a variable.
  • Create an object for the above class by passing the given string as an argument and store it in another variable.
  • Print the string before appending.
  • Append some random string to the above-obtained result string using the append() function.
  • Print the string after appending.
  • Remove some random string from the above-obtained result string using the remove() function.
  • Print the string after removing.
  • The Exit of the Program.

Below is the implementation:

# Import UserString() function from the collections module using the import keyword.
from collections import UserString


# Create a class by passing the UserString function as an argument.
class Given_String(UserString):

    # Inside the class, create a function by passing the second string as an argument
    # for appending some random string
    def append(self, str2):
        # Concatenate the second string to the given string using the string concatenation.
        self.data += str2

    # Create another function by passing the second string as an argument
    # for removing some random string from the given string
    def remove(self, str2):
        # Inside the function, remove all the second-string characters by replacing it with
        # null string using the replace() function.
        self.data = self.data.replace(str2, "")


# In the main Function
# Give the string as static input and store it in a variable.
gvn_str = "Python"
# Create an object for the above class by passing the given string as an argument
# and store it in another variable.
rsltstr = Given_String(gvn_str)
# Print the string before appending.
print("The string before appending is :", rsltstr.data)

# Append some random string to the above obtained result string using the append() function
rsltstr.append("programs")
# Print the string after appending.
print("After appending the Result string is :", rsltstr.data)

# Remove some random string from the above obtained result string using the remove() function
rsltstr.remove("rams")
# Print the string after removing.
print("After Removing the Result string is :", rsltstr.data)

Output:

The string before appending is : Python
After appending the Result string is : Pythonprograms
After Removing the Result string is : Pythonprog

Method #2: Using collections Module (User Input)

Approach:

  • Import UserString() function from the collections module using the import keyword.
  • Give the string as user input using the input() function and store it in a variable.
  • Pass the given string as an argument to the UserString() function to create a user string for the given string.
  • Store it in another variable.
  • Print the above result.
  • Create an empty user string using the UserString() function and store it in another variable.
  • Print the above obtained empty user string.
  • The Exit of the Program.

Below is the implementation:

# Import UserString() function from the collections module using the import keyword.
from collections import UserString
# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Pass the given string as an argument to the UserString() function to
# create a user string for the given string.
# Store it in another variable.
rsltusr_str = UserString(gvn_str)
# Print the above result.
print("The user string for the given string is :")
print(rsltusr_str.data)
# Create an empty user string using the UserString() function
# and store it in another variable.
print("The empty user string is :")
emty_rsltstr = UserString("")
# Print the above obtained empty user string.
print(emty_rsltstr.data)

Output:

Enter some random string = 3436hello
The user string for the given string is :
3436hello
The empty user string is :

Example2:

Approach:

  • Import UserString() function from the collections module using the import keyword.
  • Create a class by passing the UserString function as an argument.
  • Inside the class, create a function by passing the second string as an argument for appending some random string.
  • Concatenate the second string to the given string using the string concatenation.
  • Create another function by passing the second string as an argument for removing some random string from the given string.
  • Inside the function, remove all the second-string characters by replacing it with a null string using the replace() function.
  • In the main Function,
  • Give the string as user input using the input() function and store it in a variable.
  • Create an object for the above class by passing the given string as an argument and store it in another variable.
  • Print the string before appending.
  • Append some random string to the above-obtained result string using the append() function.
  • Print the string after appending.
  • Remove some random string from the above-obtained result string using the remove() function.
  • Print the string after removing.
  • The Exit of the Program.

Below is the implementation:

# Import UserString() function from the collections module using the import keyword.
from collections import UserString


# Create a class by passing the UserString function as an argument.
class Given_String(UserString):

    # Inside the class, create a function by passing the second string as an argument
    # for appending some random string
    def append(self, str2):
        # Concatenate the second string to the given string using the string concatenation.
        self.data += str2

    # Create another function by passing the second string as an argument
    # for removing some random string from the given string
    def remove(self, str2):
        # Inside the function, remove all the second-string characters by replacing it with
        # null string using the replace() function.
        self.data = self.data.replace(str2, "")


# In the main Function
# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Create an object for the above class by passing the given string as an argument
# and store it in another variable.
rsltstr = Given_String(gvn_str)
# Print the string before appending.
print("The string before appending is :", rsltstr.data)

# Append some random string to the above obtained result string using the append() function
rsltstr.append("morning all")
# Print the string after appending.
print("After appending the Result string is :", rsltstr.data)

# Remove some random string from the above obtained result string using the remove() function
rsltstr.remove("all")
# Print the string after removing.
print("After Removing the Result string is :", rsltstr.data)

Output:

Enter some random string = good
The string before appending is : good
After appending the Result string is : goodmorning all
After Removing the Result string is : goodmorning

Python Program for collections.UserString Function Read More »

Python Program for collections.UserList

Python collections.UserList():

Python has a List-like container called UserList, which is found in the collections module. This class acts as a container for List objects. This class is useful when one wants to create their own list with modified or new functionality. It can be viewed as a method of adding new behaviors to the list. This class takes a list instance as an argument and simulates a regular list. The data attribute of this class provides access to the list.

Syntax:

collections.UserList(list)

Parameters:

list: This is required. It is a list to be given as input.

Program for collections.UserList in Python

Method #1: Using collections Module (Static Input)

Approach:

  • Import UserList() function from the collections module using the import keyword.
  • Give the list as static input and store it in a variable.
  • Pass the given list as an argument to the UserList() function to create a user list for the given list.
  • Store it in another variable.
  • Print the above result.
  • Create an empty user list using the UserList() function and store it in another variable.
  • Print the above obtained empty user list.
  • The Exit of the Program.

Below is the implementation:

# Import UserList() function from the collections module using the import keyword.
from collections import UserList
# Give the list as static input and store it in a variable.
gvn_lst = [35,20,60,12,9]
# Pass the given list as an argument to the UserList() function to create a
# user list for the given list.
# Store it in another variable.
rslt_userlst = UserList(gvn_lst)
# Print the above result.
print("The user list for the given list is :")
print(rslt_userlst.data)
# Create an empty user list using the UserList() function and store it in
# another variable.
empt_usrlst = UserList()
# Print the above obtained empty user list.
print("The Empty user list is :")
print(empt_usrlst.data)

Output:

The user list for the given list is :
[35, 20, 60, 12, 9]
The Empty user list is :
[]

Example2:

Approach:

  • Import UserList() function from the collections module using the import keyword.
  • Create a class by passing the UserList function as an argument.
  • Inside the class, create a function by passing the parameter as none for stopping the deletion of items from a given list.
  • Inside the function raise some random RuntimeError.
  • Create another function by passing the parameter as none for stopping the poping of items from a given list.
  • Inside the function raise some random RuntimeError.
  •  Inside the main function, Give the list as static input and store it in a variable.
  • Create an object for the above class by passing the given list as an argument and store it in another variable.
  • Print the list before Insertion.
  • Insert an element to the above-obtained result list using the append() function.
  • Print the list after appending an element to the given list.
  • Delete an item from the list using the remove() function.
  • The Exit of the Program.

Below is the implementation:

# Import UserList() function from the collections module using the import keyword.

from collections import UserList


# Create a class by passing the UserList function as an argument.
class GivenList(UserList):

    # Inside the class, create a function by passing the parameter as none for stopping
    # the deletion of items from a given list.
    def remove(self, a=None):
        # Inside the function raise some random RuntimeError.
        raise RuntimeError("You Cannot delete an element from the given list")

    # Create another function by passing the parameter as none for stopping the
    # poping of items from a given list.
    def pop(self, a=None):
        # Inside the function raise some random RuntimeError.
        raise RuntimeError("You Cannot delete an element from the given list")


# Inside the main function
# Give the list as static input and store it in a variable.
gvn_lst = [22, 33, 44, 55]
# Create an object for the above class by passing the given list as an argument
# and store it in another variable.
lst = GivenList(gvn_lst)
# Print the list before Insertion.
print("The list before Insertion :")
print(lst)
# Insert an element to the above-obtained result list using the append() function.
lst.append(66)
# Print the list after appending an element to the given list.
print("The list before Insertion :")
print(lst)

# Delete an item from the list using the remove() function.
lst.remove()

Output:

The list before Insertion :
[22, 33, 44, 55]
The list before Insertion :
[22, 33, 44, 55, 66]
Traceback (most recent call last):
File "jdoodle.py", line 38, in <module>
lst.remove()
File "jdoodle.py", line 13, in remove
raise RuntimeError("You Cannot delete an element from the given list")
RuntimeError: You Cannot delete an element from the given list

Method #2: Using collections Module (User Input)

Approach:

  • Import UserList() function from the collections module using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the given list as an argument to the UserList() function to create a user list for the given list.
  • Store it in another variable.
  • Print the above result.
  • Create an empty user list using the UserList() function and store it in another variable.
  • Print the above obtained empty user list.
  • The Exit of the Program.

Below is the implementation:

# Import UserList() function from the collections module using the import keyword.
from collections import UserList
# 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 UserList() function to create a
# user list for the given list.
# Store it in another variable.
rslt_userlst = UserList(gvn_lst)
# Print the above result.
print("The user list for the given list is :")
print(rslt_userlst.data)
# Create an empty user list using the UserList() function and store it in
# another variable.
empt_usrlst = UserList()
# Print the above obtained empty user list.
print("The Empty user list is :")
print(empt_usrlst.data)

Output:

Enter some random List Elements separated by spaces = 8 4 2 5 1
The user list for the given list is :
[8, 4, 2, 5, 1]
The Empty user list is :
[]

Example 2:

Approach:

  • Import UserList() function from the collections module using the import keyword.
  • Create a class by passing the UserList function as an argument.
  • Inside the class, create a function by passing the parameter as none for stopping the deletion of items from a given list.
  • Inside the function raise some random RuntimeError.
  • Create another function by passing the parameter as none for stopping the poping of items from a given list.
  • Inside the function raise some random RuntimeError.
  •  Inside the main function,
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Create an object for the above class by passing the given list as an argument and store it in another variable.
  • Print the list before Insertion.
  • Insert an element to the above-obtained result list using the append() function.
  • Print the list after appending an element to the given list.
  • Delete an item from the list using the remove() function.
  • The Exit of the Program.

Below is the implementation:

# Import UserList() function from the collections module using the import keyword.

from collections import UserList


# Create a class by passing the UserList function as an argument.
class GivenList(UserList):

    # Inside the class, create a function by passing the parameter as none for stopping
    # the deletion of items from a given list.
    def remove(self, a=None):
        # Inside the function raise some random RuntimeError.
        raise RuntimeError("You Cannot delete an element from the given list")

    # Create another function by passing the parameter as none for stopping the
    # poping of items from a given list.
    def pop(self, a=None):
        # Inside the function raise some random RuntimeError.
        raise RuntimeError("You Cannot delete an element from the given list")


# Inside the main function
# 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()))

# Create an object for the above class by passing the given list as an argument
# and store it in another variable.
lst = GivenList(gvn_lst)
# Print the list before Insertion.
print("The list before Insertion :")
print(lst)
# Insert an element to the above-obtained result list using the append() function.
lst.append(66)
# Print the list after appending an element to the given list.
print("The list before Insertion :")
print(lst)

# Delete an item from the list using the remove() function.
lst.remove()

Output:

Enter some random List Elements separated by spaces = 6 8 25 5
The list before Insertion :
[6, 8, 25, 5]
The list before Insertion :
[6, 8, 25, 5, 66]
Traceback (most recent call last):
File "jdoodle.py", line 41, in <module>
lst.remove()
File "jdoodle.py", line 13, in remove
raise RuntimeError("You Cannot delete an element from the given list")
RuntimeError: You Cannot delete an element from the given list

 

Python Program for collections.UserList Read More »