Author name: Vikram Chiluka

Python Numpy matrix.itemset() Function

NumPy Library 

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

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

Numpy matrix.itemset() Function:

We can set the items in a given matrix using the matrix.itemset() method of the Numpy module by passing the index number and the item as arguments.

Syntax:

 matrix.itemset(index, item)

Return Value:

A new matrix containing item is returned by the itemset() function.

Numpy matrix.itemset() Function in Python

For 2-Dimensional (2D) Matrix 

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing some random 2D matrix as arguments to it and store it in a variable
  • Pass the index(row, column) and item/value as an argument to the itemset() function and apply it to the given matrix.
  • Here it inserts the given item at the specified index in a matrix(inserts 50 at 0th row, 1st col).
  • Store it in another variable
  • Print the given matrix after inserting an item at the specified index.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing 
# some random 2D matrix as arguments to it and store it in a variable
gvn_matrx = np.matrix('[2, 1; 6, 3]')
            
# Pass the index(row, column) and item/value as an argument to the itemset() function and 
# apply it to the given matrix.
# Here it inserts the given item at the specified index in a matrix(inserts 50 at 0th row, 1st col).
# Store it in another variable
gvn_matrx.itemset((0, 1), 50)
# Print the given matrix after inserting an item at the specified index
print("The given matrix after inserting an item {50} at the specified index(0th row, 1st col):")
print(gvn_matrx)

Output:

The given matrix after inserting an item {50} at the specified index(0th row, 1st col):
[[ 2 50]
 [ 6 3]]

For 3-Dimensional (3D) Matrix 

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing some random 3D matrix as arguments to it and store it in a variable
  • Pass the index(row, column) and item/value as an argument to the itemset() function and apply it to the given matrix.
  • Here it inserts the given item at the specified index in a matrix(inserts 50 at 0th row, 1st col).
  • Store it in another variable
  • Print the given matrix after inserting an item at the specified index.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing 
# some random 3D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[2, 4, 1; 8, 7, 3; 10, 9, 5]')
            
# Pass the index(row, column) and item/value as an argument to the itemset() function and 
# apply it to the given matrix.
# Here it inserts the given item at the specified index in a matrix(inserts 100 at 1st row, 2nd col).
# Store it in another variable
gvn_matrx.itemset((1, 2), 100)
# Print the given matrix after inserting an item at the specified index
print("The given matrix after inserting an item {100} at the specified index(1st row, 2nd col):")
print(gvn_matrx)

Output:

The given matrix after inserting an item {100} at the specified index(1st row, 2nd col):
[[ 2 4 1]
 [ 8 7 100]
 [ 10 9 5]]

Python Numpy matrix.itemset() Function Read More »

Difference between != and is not operator in Python

In this tutorial, let us look at the difference between != and is not operator in Python.

!= is defined in Python as the not equal to operator. If the operands on either side are not equal, it returns True; otherwise, it returns False.

The is not operator checks whether the id() of two objects is the same or not. If they are the same, it returns False; otherwise, it returns True. And the is not operator returns True if the operands on either side are not equal, and False if they are.

Difference between != and is not operator in Python

Method #1: Using is not Operator on Numbers

Approach:

  • 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.
  • Check if both the given numbers are equal or not using the is not operator.
  • Print the id of both the given numbers using the id() function.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
gvn_num1 = 5
# Give the second number as static input and store it in another variable.
gvn_num2 = 5

# Check if both the given numbers are equal or not using the is not operator
print(gvn_num1 is not gvn_num2)
# Print the id of both the given numbers using the id() function
print(id(gvn_num1), id(gvn_num2))

Output:

False
11256192 11256192

Explanation:

Here it returns the output as False since both variables
gvn_num1 and gvn_num2 referred to the same data 5

Method #2: Using is not Operator on Strings

Approach:

  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Check if both the given strings are equal using the is not operator.
  • Print the id of both the given strings using the id() function.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable.
gvn_str1 = "pythonprogarms"
# Give the second string as static input and store it in another variable.
gvn_str2 = "pythonprogarms"

# Check if both the given strings are equal using the is not operator
print(gvn_str1 is not gvn_str2)
# Print the id of both the given strings using the id() function
print(id(gvn_str1), id(gvn_str2))

Output:

False
140627397413232 140627397413232

Explanation:

Here it returns the output as False since both the string variables
gvn_str1 and gvn_str2 referred to the same data "pythonprogarms"

Method #3: Using is not Operator on Lists

# Give the first list as static input and store it in a variable.
gvn_lst1 = [10, 15, 20]
# Give the second list as static input and store it in another variable.
gvn_lst2 = [10, 15, 20]

# Check if both the given lists are equal using the is not operator
print(gvn_lst1 is not gvn_lst2)
# Print the id of both the given lists using the id() function
print(id(gvn_lst1), id(gvn_lst2))

Output:

True
140627403656880 140627397425344

Explanation:

Here it returns the output as True since both the variables
gvn_lst1 and gvn_lst2 have distinct memory addresses even if 
both variables contain the same data.

Method #4: Using != Operators on Numbers

Approach:

  • 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.
  • Check if both the given numbers are equal or not using the != operator.
  • Print the id of both the given numbers using the id() function.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
gvn_num1 = 5
# Give the second number as static input and store it in another variable.
gvn_num2 = 5

# Check if both the given numbers are equal or not using the != operator
print(gvn_num1 != gvn_num2)
# Print the id of both the given numbers using the id() function
print(id(gvn_num1), id(gvn_num2))

Output:

False
11256192 11256192

Method #5: Using != Operators on Strings

Approach:

  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Check if both the given strings are equal or not using the != operator.
  • Print the id of both the given strings using the id() function.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable.
gvn_str1 = "pythonprogarms"
# Give the second string as static input and store it in another variable.
gvn_str2 = "pythonprogarms"

# Check if both the given strings are equal or not using the != operator
print(gvn_str1 !=  gvn_str2)
# Print the id of both the given strings using the id() function
print(id(gvn_str1), id(gvn_str2))

Output:

False
140627397413232 140627397413232

Method #6: Using != Operators on Lists

# Give the first list as static input and store it in a variable.
gvn_lst1 = [10, 15, 20]
# Give the second list as static input and store it in another variable.
gvn_lst2 = [10, 15, 20]

# Check if both the given lists are equal or not using the !=  operator
print(gvn_lst1 != gvn_lst2)
# Print the id of both the given lists using the id() function
print(id(gvn_lst1), id(gvn_lst2))

Output:

False
140627397115488 140627397114768

Method #7: Comparing != and is not operators

gvn_lst1 = []
gvn_lst2 = []
gvn_lst3 = gvn_lst1

# Applying != operator for comparing gvn_lst1 and gvn_lst2
if (gvn_lst1 != gvn_lst2):
    print("True")
else:
    print("False")
 
# Applying is not operator for comparing gvn_lst1 and gvn_lst2
if (gvn_lst1 is not gvn_lst2):
    print("True")
else:
    print("False")
    
# Applying is not operator for comparing gvn_lst1 and gvn_lst3
if (gvn_lst1 is not gvn_lst3):
    print("True")
else:
    print("False")

# Concatenating given third and secondlists and saving it as a given third list
gvn_lst3 = gvn_lst3 + gvn_lst2

# Applying is not operator for comparing gvn_lst1 and gvn_lst3
if (gvn_lst1 is not gvn_lst3):
    print("True")
else:
    print("False")

Output:

False
True
False
True

Explanation:

  • Because both gvn_lst1 and gvn_lst2 are empty lists, the output of the first condition is “False”.
  • Second, if the condition is “True,” it means that two empty lists are located in different memory locations. As a result, gvn_lst1 and gvn_lst2 correspond to distinct items. We can test it using Python’s id() function, which returns an object’s “identity.”
  • If the condition is “False,” the output of the third is “False,” because both gvn_lst1 and gvn_lst3 point to the same object.
  • Since the concatenation of two lists always produces a new list, the output of the fourth if the condition is “True.”

Difference between != and is not operator in Python Read More »

How to Make a Terminal Progress Bar using tqdm in Python

Whenever we install a Python library, module, or software, we see a progress bar appear on the screen, which denotes a small progress bar that estimates how long the process will take to complete or render. It gives the impression of activity and can help to relax us. We’ve all seen the various progress bars.

The percentage of progress made in completing a task is represented by progress bars. The progress can be calculated by dividing the number of items processed by the total number of input items. Several factors influence the progress bar, including network speed, latency, and whether or not data is persisting into local storage to provide a more accurate ETA (Estimated Time of Arrival).

Using the Python external library tqdm, we can create simple and easy progress bars.

Python tqdm library:

The tqdm is a Python library that provides functions that wrap around the specified iterable and output a smart progress bar.
Python is a popular programming language for performing computationally intensive tasks that take a long time to complete.
The progress of these tasks is indicated by a tqdm progress bar.

The name “tqdm” is derived from the Arabic word “taqadum,” which means “progress.”
The library does support customizable progress bars, but at its core, the code tqdm(iterable) is sufficient to get you started with a smart progress metre displaying the iterable’s progress.

Installation

pip install tqdm

Use of tqdm:

To use tqdm, simply add your code between tqdm() after importing the library into your code. You must ensure that the code you insert between the tqdm() function is iterable or it will not work.

Approach:

  • Import tqdm from tqdm module using the import keyword.
  • Loop till the 7e^5 to make the progress bar using the for loop.
  • The Exit of the Program.

Below is the implementation:

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm

# Loop till the 7e^5 to make the progress bar using the for loop
for k in tqdm(range(int(7e5))):
    pass

Output:

100%|██████████| 700000/700000 [00:00<00:00, 1540207.48it/s]

Parameters of tqdm

1) desc: This is used to specify the description of your progress bar

Syntax:

tqdm (self, iterable, desc= "text")

Example

Approach:

  • Import tqdm from tqdm module using the import keyword.
  • Import sleep from time module using the import keyword.
  • Loop till the 80 by specifying any sample description using the desc argument.
  • Sleep for 1 second using the sleep() function.
  • The Exit of the Program.

Below is the implementation:

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 by specifying any sample description using the desc argument
for i in tqdm(range(0, 80), desc ="PythonProgarms"):
  # Sleep for 1 second using the sleep() function
    sleep(.1)

Output:

PythonProgarms: 100%|██████████| 80/80 [00:08<00:00, 9.75it/s]

2) total: It specifies the total number of expected iterations if not specified already or requires any modification.

Syntax:

tqdm (self, iterable, total= 500)

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till 80 by specifying the total number of expected iterations using the total argument
for i in tqdm(range(0, 80), total = 400, desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)

Output:

PythonProgarms: 20%|██ | 80/400 [00:16<01:04, 4.93it/s]

3) disable: If you wish to totally disable the progress bar, use this parameter.

Syntax:

tqdm (self, iterable, disable=True)

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and if we set disable as true then it will not display progress bar
for i in tqdm(range(0, 80), disable = True, desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)
 
print("The iteration is Success")

Output:

The iteration is Success

4) ncols: It represents the total width of the output message. If left unspecified, it defaults to the size of the window. The ncols parameter can be used to fix this.

Syntax:

tqdm (self, iterable, ncols= 100)

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and here specify the width of output message using the ncols argument
for i in tqdm(range(0, 80), ncols = 70, desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)

Output:

PythonProgarms: 100%|█████████████████| 80/80 [00:16<00:00, 4.94it/s]

5) mininterval: Using this parameter, we can easily modify the minimum progress display update. The default value is 0.1 seconds.

Syntax:

tqdm (self, iterable, mininterval=3)

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and min interval shows the minimum progress display update
for i in tqdm(range(0, 80), mininterval = 4, desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)

Output:

PythonProgarms: 100%|██████████| 80/80 [00:16<00:00, 4.99it/s]

6) ascii: ASCII characters can be used to fill the progress bar of your choice.

Syntax:

tqdm (self, iterable, ascii= "123456789$", desc="text")

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and we filled the progress bar with the ascii characters
for i in tqdm(range(0, 80), ascii ="123456789$"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)
Output:
100%|$$$$$$$$$$| 80/80 [00:16<00:00, 4.95it/s]

7) unit: The default unit of time is “it,” which can be changed to your preferred unit by using this argument.

Syntax:

tqdm (self, iterable, unit= "ticks")

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and here if we specify unit as ticks we get number of ticks per second
for i in tqdm(range(0, 80), unit =" ticks", desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)

Output:

PythonProgarms: 100%|██████████| 80/80 [00:16<00:00, 4.94 ticks/s]

8) initial: The progress bar’s initial value is set to 0. If you want to change this, you may use this argument to set the progress bar to any value you want.

Syntax:

tqdm (self, iterable, initial=50)

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and if we specify initial argument then it will be the starting value of the progress bar
for i in tqdm(range(0, 80), initial = 20, desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)

Output:

PythonProgarms: 100it [00:16, 4.95it/s]

How to Make a Terminal Progress Bar using tqdm in Python Read More »

How to get synonyms/antonyms from NLTK WordNet in Python?

The NLTK Wordnet can be used to find word synonyms and antonyms. To comprehend the lexical semantics of the terms in the document, the NLTK Corpus package is used to read the corpus.

WordNet is a big English lexical database. The nouns, verbs, adjectives, and adverbs are grouped into some set of cognitive synonyms, which are called Synsets. Synsets are linked together by conceptual-semantic and lexical relationships.

A WordNet is a lexical database that contains semantic relationships between words and their meanings. WordNet semantic relations include hypernyms, synonyms, holonyms, hyponyms, and meronyms. The NLTK WordNet allows the use of synsets to find words inside the WordNet together with their usages, meanings, and examples. The goal of NLTK WordNet is to find representations between senses. With lexical semantics, relationship type detection is connected to WordNet. A dog can be a mammal, as represented by a “IS-A” relationship type sentence.

Thus, NLTK Wordnet is used to identify relationships between words in a document, as well as spam detection, duplication detection, and characteristics of words inside a written text based on their POS Tags.

The structure of WordNet makes it an excellent tool for computational linguistics and natural language processing.

  • WordNet appears to be similar to a thesaurus in that it puts words together depending on their meanings. There are, however, some key distinctions.
  • First, WordNet connects not just word forms (strings of letters), but also precise senses of words. As a result, words in the network that are close to one another are semantically disambiguate.
  • Second, WordNet labels the semantic relationships between words, whereas thesaurus word groupings do not follow any defined pattern other than meaning similarity.

Python Program to get synonyms/antonyms from NLTK WordNet

Follow the below steps to execute the methods.

Steps:

pip install nltk

Output:

Collecting nltk
Downloading nltk-3.7-py3-none-any.whl (1.5 MB)
---------------------------------------- 1.5/1.5 MB 1.8 MB/s eta 0:00:00
Collecting regex>=2021.8.3
Downloading regex-2022.8.17-cp310-cp310-win_amd64.whl (263 kB)
---------------------------------------- 263.0/263.0 kB 2.7 MB/s eta 0:00:00
Collecting joblib
Downloading joblib-1.1.0-py2.py3-none-any.whl (306 kB)
---------------------------------------- 307.0/307.0 kB 4.7 MB/s eta 0:00:00
Collecting tqdm
Downloading tqdm-4.64.0-py2.py3-none-any.whl (78 kB)
---------------------------------------- 78.4/78.4 kB 2.2 MB/s eta 0:00:00
Requirement already satisfied: click in c:\users\cirus\appdata\local\programs\python\python310\lib\site-packages (from nltk) (8.1.2)
Requirement already satisfied: colorama in c:\users\cirus\appdata\local\programs\python\python310\lib\site-packages (from click->nltk) (0.4.4)
Installing collected packages: tqdm, regex, joblib, nltk

Successfully installed joblib-1.1.0 nltk-3.7 regex-2022.8.17

2)downloading wordnet and omw-1.4

import nltk.corpus
nltk.download('wordnet')

Output:

[nltk_data] Downloading package wordnet to /root/nltk_data...
True
nltk.download('omw-1.4')

Output:

[nltk_data] Downloading package omw-1.4 to /root/nltk_data...
True

Method #1: Getting the definition,type and examples of the word

Approach:

  • Import wordnet from corpus of nltk module using the import keyword.
  • Pass the word to find synsets to the synsets() function.
  • Print the example, and type of the word using the name() function.
  • Print just the word.
  • Print the definition of the word using the definition() function.
  • Print the sample sentences where the word is used using the examples() function.
  • The Exit of the Program.

Below is the implementation:

# Import wordnet from corpus of nltk module using the import keyword
from nltk.corpus import wordnet

# Pass the word to find synsets like so:
synsetsofWord = wordnet.synsets("Price")

# Printing the example,type of the word using the name() function
print('Word and type of the word {price}',synsetsofWord[0].name())

# Printing just the word
print('Printing the word',synsetsofWord[0].lemmas()[0].name())

# Printing the definition of the word using the definition() function
print('Definition of the word:',synsetsofWord[0].definition())

# Printing the sample sentences where the word is used using the examples() function
print('Example sentences where the word is used:',synsetsofWord[0].examples())

Output:

Word and type of the word {price} monetary_value.n.01
Printing the word monetary_value
Definition of the word: the property of having material worth (often indicated by the amount of money something would bring if sold)
Example sentences where the word is used: ['the fluctuating monetary value of gold and silver', 'he puts a high price on his services', "he couldn't calculate the cost of the collection"]

Method #2: Getting the synonyms and antonyms list of the word

Approach:

  • Import nltk module using the import keyword
  • Import wordnet from corpus of nltk module using the import keyword
  • Create an empty list to store the synonyms
  • Create an empty list to store the antonyms
  • Loop in the synsets of the word using the for loop
  • Loop in the above using another nested for loop
  • Add the synonym of the word to the synonyms list using the append() function
  • Add the antonyms to the antonyms list.
  • Print all the unique synonyms from the above resultant synonyms list using the set() function.
  • Print all the unique antonyms from the above resultant antonyms list using the set() function.
  • The Exit of the Program.

Below is the implementation:

# Import nltk module using the import keyword
import nltk
# Import wordnet from corpus of nltk module using the import keyword
from nltk.corpus import wordnet
# Create an empty list to store the synonyms
synonyms_lst = []
# Create an empty list to store the antonyms
antonyms_lst = []

# Loop in the synsets of the word using the for loop
for syn in wordnet.synsets("good"):
  # Loop in the above  using another nested for loop
    for l in syn.lemmas():
        # Add the synonym of the word to the synonyms list using the append() function
        synonyms_lst.append(l.name())
        # Adding the antonyms to the antonyms list
        if l.antonyms():
            antonyms_lst.append(l.antonyms()[0].name())

# Print all the unique synonyms from the above resultant synonyms list
# using the set() function
print('The synonyms of the word {good}',set(synonyms_lst))
# Print all the unique antonyms from the above resultant antonyms list
# using the set() function
print('The antonyms of the word {good}',set(antonyms_lst))

Output:

The synonyms of the word {good} {'in_force', 'undecomposed', 'safe', 'well', 'trade_good', 'proficient', 'unspoilt', 'effective', 'ripe', 'just', 'dependable', 'good', 'expert', 'sound', 'thoroughly', 'beneficial', 'skillful', 'salutary', 'honest', 'right', 'respectable', 'estimable', 'in_effect', 'secure', 'unspoiled', 'upright', 'full', 'dear', 'serious', 'commodity', 'skilful', 'near', 'goodness', 'adept', 'honorable', 'practiced', 'soundly'}
The antonyms of the word {good} {'evilness', 'bad', 'evil', 'badness', 'ill'}

Method #3: Comparing the Similarity Index of Two Words

Below is the implementation:

# Import nltk module using the import keyword
import nltk
# Import wordnet from corpus of nltk module using the import keyword
from nltk.corpus import wordnet

# Pass any two random words as an argument to the synset() function of wordnet to
# find similarity of the both the words and store them in two separate variables
# Here v represents the tag verb
word_1 = wordnet.synset('price.v.01') 
word_2 = wordnet.synset('run.v.01')
# Printing the similarity of the both the words passed using the wup_similarity() function
print(word_1.wup_similarity(word_2))

Output:

0.2857142857142857

How to get synonyms/antonyms from NLTK WordNet in Python? Read More »

How to Download Instagram profile pic using Python

In this post, let us look at how to download Instagram profile pictures using python.

Everyone nowadays utilizes social media, and one of the most popular apps is Instagram. Its users enjoy its material, which includes text, effects, stickers, and so on. One of them is the video and reel feature.

Web scraping is a task that needs an understanding of how web pages are structured. To obtain the required information from web pages, one must first understand the structure of the web pages, then analyze the tags that contain the required information, and finally the attributes of those tags.

It is intended for programmers, data analysts, scientists, and engineers who are already proficient in extracting content from web pages with BeautifulSoup.

You may have noticed that there are numerous websites that are both complex and lengthy, making it difficult to find anything. Python includes some built-in libraries to help us with searching, modifying, and iterating, such as Requests, Xml, Beautiful Soup, Selenium, Scrapy, and so on.

Python Requests

To understand how the requests module works, you must first understand what happens when you browse the web and how it instantaneously displays the data we were hoping to see.

When you click a link, we make an HTTP (Hypertext Transfer Protocol) request to the server that hosts the requested page.

When the server receives the request, it returns the requested content to us.

The two most useful HTTP requests are GET and POST.

Python Code to Download Instagram profile pic

Method #1: Using instaloader Module

Python and the PyCharm IDE must be installed on your computer (or you can use any of your IDE)

We can use the instaloader module to download the profile picture of any Instagram account by simply entering the user’s Instagram handle.

Type the below command to install the instaloader module:

pip install instaloader

Output:

Looking in indexes: 
Collecting instaloader Downloading 
instaloader-4.9.3.tar.gz (60 kB) |████████████████████████████████| 60 
kB 2.7 MB/s Requirement already satisfied: requests>=2.4 in /usr/local/lib/
python3.7/dist-packages (from instaloader) (2.23.0) Requirement already 
satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages 
(from requests>=2.4->instaloader) (3.0.4) Requirement already satisfied: 
idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages 
(from requests>=2.4->instaloader) (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>=2.4->instaloader) (1.24.3) Requirement 
already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/
dist-packages (from requests>=2.4->instaloader) (2022.6.15) 
Building wheels for collected packages: instaloader Building wheel for
instaloader (setup.py) ... done Created wheel for instaloader: 
filename=instaloader-4.9.3-py3-none-any.whl size=62303 
sha256=eaecaa74aa9702c5841e4f698afa7e357a59823c20816bb5dfad4f7193ec40a6 
Stored in directory: /root/.cache/pip/wheels/38/d0/76/393aa35939
4d16f2744f5bf8cb71cddb68ad8944de7722a4bd Successfully built 
instaloader Installing collected packages: instaloader Successfully 
installed instaloader-4.9.3

Approach:

  • Import instaloader module using the import keyword
  • Give the instagram user name as user input using the input() function and store it in a variable
  • Download the instagram profile picture using the download_profile() function by passing the above insta username, profile_pic_only as True as arguments to it.
  • Print some random text for acknowledgment.
  • The Exit of the Program.

Below is the implementation:

# Import instaloader module using the import keyword
import instaloader
# Give the insta user name as user input using the input() function and 
# store it in a variable
instagramUsername = input("Enter some random instagram username = ")
# Download the instagram profile picture using the download_profile() function
# by passing the above insta username, profile_pic_only as True as arguments to it
instaloader.Instaloader().download_profile(instagramUsername , profile_pic_only=True)
# Print some random text for acknowledgment
print("The instagram profile picture is download succesfully!!")

Output:

The instagram profile picture is download succesfully!!

Method #2: Using BeautifulSoup Module

Beautiful Soup, out of all the available Python libraries, is the one that performs web scraping relatively faster than the others. There are times when we need to use Beautiful Soup to find all of the children of a certain element.

Approach:

  • Import requests, BeautifulSoup, json, random and os.path modules using the import keyword.
  • Give the website URL of instagram and store it in a variable.
  • Give the instagram username as user input using the input() function and store it in another variable.
  • Get the response using the requests module get() function.
  • Check if the response is success(here ok attribute specifies request is success).
  • Get the text of the response using the text attribute and save it in a variable.
  • Create a random file name to store using the random function and save it in a variable (here .jpg specifies image extension).
  • Check if the above file exists in our system using the isfile() function.
  • If the file doesn’t exists then we can save with the above filename.
  • Open the above file in the write binary mode.
  • Get the response from the string url using the requests module get() function.
  • If we get in any error then we print the error.
  • Else we write the image to the file using the write() function.
  • The Exit of the Program.

Below is the implementation:

# Import requests, BeautifulSoup, json, random and 
# os.path modules using the import keyword
import requests
from bs4 import BeautifulSoup as bs
import json
import random
import os.path

# Give the website URL of instagram and store it in a variable
instagramUrl='https://www.instagram.com'

# Give the insta username as user input using the input() function and 
# store it in another variable
instagramUsername= input("Enter some random instagram username =")

# Get the response using the requests module get() function
response = requests.get(f"{instagramUrl}/{instagramUsername}/")

# Check if the response is success(here ok attribute specifies request is success)
if response.ok:
    # Get the text of the response using the text attribute and save in a variable
    html=response.text
    bs_html=bs(html, features="lxml")
    bs_html=bs_html.text
    index=bs_html.find('profile_pic_url_hd')+21
    remaining_text=bs_html[index:]
    remaining_text_index=remaining_text.find('requested_by_viewer')-3
    string_url=remaining_text[:remaining_text_index].replace("\\u0026","&")

    print(string_url, "\n \n downloading..........")

while True:
    # Create a random file name to store using the random function and save it in a variable (here .jpg specifies image extension)
    filename='pic'+str(random.randint(1, 100000))+'.jpg'
    # Check if the above file exists in our system using the isfile() function
    file_exists = os.path.isfile(filename)
    # If the file doesn't exists then we can save with the above filename
    if not file_exists:
        # Open the above file in the write binary mode
        with open(filename, 'wb+') as handle:
            # Get the response from the string url using the requests module get() function
            response = requests.get(string_url, stream=True)
            # If we get in any error then we print the error
            if not response.ok:
                print(response)
            # Else we write the image to the file using the write() function
            for block in response.iter_content(1024):
                if not block:
                    break
                handle.write(block)
    else:
        continue
    break
print("The instagram profile picture is download succesfully!!")

Output:

Enter some random instagram username = virat.kohli
The instagram profile picture is download succesfully!!

Image:

insta profile photo downloader

How to Download Instagram profile pic using Python Read More »

Python String split()

The split() method in python splits a string into a list based on the specified separator. The separator can be specified, however, the default separator is any whitespace.

Syntax:

string.split(separator, maxsplit)

Parameters

  • separator: This is optional. The separator to be used when separating the string. By default, any whitespace serves as a separator.
  • maxsplit: This is optional. It represents the number of splits to perform. The default value is -1, which represents “all occurrences.”

Return Value:

A list of strings is returned by the split() method

NOTE

When maxsplit is specified, the list will have the number of elements
specified plus one.

Python String split()

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

Approach:

  • Give the first string as static input and store it in a variable
  • Apply split() function on the given first string and print the result.
  • Here it splits the string based on the white spaces as there is no separator argument passed.
  • Give the second string as static input and store it in another variable
  • Apply split() function on the given second string by passing the separator as an argument to it and print the result.
  • Here it splits the string based in the ‘@’ symbol
  • Similarly split based on other separators and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable
gvnstring_1 = 'Hello this is pythonprograms'

# Apply split() fuction on the given first string and print the result. 
# Here it splits the string based on the white spaces as there 
# is no separator argument passed.
print("Splitting gvnstring_1 based on spaces:", gvnstring_1.split())

# Give the second string as static input and store it in another variable
gvnstring_2 = 'Welcome@to@pythonprograms'

# Apply split() function on the given second string by 
# passing the separator as an argument to it and print the result. 
# Here it splits the string based in the '@' symbol
print("Splitting gvnstring_2 based on '@' symbol:", gvnstring_2.split('@'))

# Similary split based on other separators
gvnstring_3 = 'Welcome:to:pythonprograms'
print("Splitting gvnstring_3 based on ':' symbol:", gvnstring_3.split(':'))

Output:

Splitting gvnstring_1 based on spaces: ['Hello', 'this', 'is', 'pythonprograms']
Splitting gvnstring_2 based on '@' symbol: ['Welcome', 'to', 'pythonprograms']
Splitting gvnstring_3 based on ':' symbol: ['Welcome', 'to', 'pythonprograms']

Method #2: When maxsplit argument is passed (Static Input)

Approach:

  • Give the first string as static input and store it in a variable
  • Apply split() fuction on the given first string by passing space, maxsplit = 0 as arguments to it and print the result.
  • Here it splits the string based on the white spaces but max split is given as 0. So it doesn’t split.
  • Give the second string as static input and store it in another variable
  • Apply split() fuction on the given second string by passing the separator as ‘@’ and maxsplit = 2 as arguments to it and print the result.
  • Here 2 specifies we are going to split two times if the @ symbol is present.
  • Similarly split based on other separators.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable
gvnstring_1 = 'Hello this is btechgeeks'

# Apply split() fuction on the given first string by passing space,
# maxsplit = 0 as arguments to it and print the result. 
# Here it splits the string based on the white spaces but max split is given as 0 
# So it doesn't split
print("Splitting gvnstring_1 based on spaces and maxsplit = 0:")
print(gvnstring_1.split(' ', 0))

# Give the second string as static input and store it in another variable
gvnstring_2 = 'Welcome to@btechgeeks'

# Apply split() fuction on the given second string by passing the separator as '@' and 
# maxsplit = 2 as arguments to it and print the result. 
# Here 2 specifies we are going to split two times if the @ symbol is present
print("Splitting gvnstring_2 based on '@' symbol and maxsplit = 2:")
print(gvnstring_2.split('@', 2))

# Similary split based on other separators
gvnstring_3 = 'Welcome:to:btechgeeks'
print("Splitting gvnstring_3 based on ':' symbol and maxsplit = 1:")
print(gvnstring_3.split(':', 1))

Output:

Splitting gvnstring_1 based on spaces and maxsplit = 0:
['Hello this is btechgeeks']
Splitting gvnstring_2 based on '@' symbol and maxsplit = 2:
['Welcome to', 'btechgeeks']
Splitting gvnstring_3 based on ':' symbol and maxsplit = 1:
['Welcome', 'to:btechgeeks']

Method #3: Using split() Functions (User Input)

Approach:

  • Give the first string as user input using the input() function and store it in a variable.
  • Give the second string as user input using the input() function and store it in another variable.
  • Apply split() function on the given string by passing the given separator as an argument to it and print the result.
  • Here it splits the string based in the given separator.
  • The Exit of the Program.

Below is the implementation:

# 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 string as user input using the input() function 
# and store it in another variable
gvn_separator = input("Enter some random separator = ")

# Apply split() function on the given string by passing the given separator 
# as an argument to it and print the result. 
# Here it splits the string based in the given separator 
print("Splitting the given string {",gvn_str,"} based on the given separator{",gvn_separator,"}:")
print(gvn_str.split(gvn_separator))

Output:

Enter some random string = hello&this&is&btechgeeks
Enter some random separator = &
Splitting the given string { hello&this&is&btechgeeks } based on the given separator{ & }:
['hello', 'this', 'is', 'btechgeeks']

Method #4: When maxsplit argument is passed (User Input)

# Give the string as user input using the input() function and store it in a variable
gvn_string= 'Hello#this#is#pythonprograms'

# Give the separator value as user input using the input() function 
# and store it in another variable
gvn_separator = input("Give some random separator = ")

# Give the maxsplit value as user input using the int(), input() function 
# and store it in another variable
gvn_maxsplit = int(input("Give some random maxsplit value = "))

# Apply split() function on the given string by passing the given separator 
# and maxsplit values as arguments to it to split the string based on the
# given separator and maxsplit values
print("Splitting the given string based on", gvn_separator,"and maxsplit =",gvn_maxsplit,":")
print(gvn_string.split(gvn_separator, gvn_maxsplit))

Output:

Give some random separator = #
Give some random maxsplit value = 2
Splitting the given string based on # and maxsplit = 2 :
['Hello', 'this', 'is#pythonprograms']

Python String split() Read More »

FuzzyWuzzy Python library

In this post,  let us look at how to use the Python built-in fuzzyWuzzy library to match the string and determine how they are similar using various examples.

Python has a few methods for comparing two strings. A few of the most common methods are listed below.

  • Using Regex
  • Simple Compare
  • Using dfflib

FuzzyBuzzy library in Python:

The FuzzyBuzzy library was created to compare to strings. To compare strings, we have other modules such as regex and difflib. However, FuzzyBuzzy is one-of-a-kind. Instead of true, false, or string, the methods in this library return a score out of 100 based on how well the strings match.

The process of finding strings that match a given pattern is known as fuzzy string matching. To calculate the differences between sequences, it employs Levenshtein Distance.

It is an open-source library developed and released by SeatGeek.

This library can assist in mapping databases that lack a common key, such as joining two tables by company name, which differs in both tables.

Example1:

# Give the string as static input and store it in a variable.
gvn_str1 = "Hello this is btechgeeks"  
# Give the string as static input and store it in a variable.
gvn_str2 = "Hello this is btechgeeks"  

# Check if both the given strings are equal using the if conditional statement
comparision_rslt = gvn_str1 == gvn_str2  
# Print the result of comparision
print(comparision_rslt)

Output:

True

FuzzyWuzzy Python library

Type the below command to install the fuzzywuzzy library:

pip install fuzzywuzzy

Now type the following command:

pip install python-Levenshtein

Method #1: Using Fuzz.ratio() method

The fuzz module is used to compare two strings at the same time. This function returns a score out of 100 after comparison using the various methods.

Fuzz.ratio() function:

It is one of the most important fuzz module methods. It compares the string and assigns a score based on how accurately the given string matches.

Approach:

  • Import fuzz from fuzzywuzzy module using the import keyword
  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Check if both the given strings are similar using the fuzz.ratio() function by passing given both strings as arguments to it.
  • Here it returns a score out of 100, which indicates how much percent they are similar out of 100.
  • Similarly, check with other strings and print the result.
  • The Exit of the Program.

Below is the implementation:

# Import fuzz from fuzzywuzzy module using the import keyword
from fuzzywuzzy import fuzz  

# Give the first string as static input and store it in a variable.
gvn_str1 = "Hello this is btechgeeks"  
# Give the second string as static input and store it in another variable.
gvn_str2 = "Hello this is btechgeeks"  

# Check if both the given strings are similar using the fuzz.ratio() function
# by passing given both strings as arguments to it.
# Here it returns a score out of 100, which indicates how much percent 
# they are similar out of 100.
print(fuzz.ratio(gvn_str1, gvn_str2))
  
# Similarly check with other strings and print the result
print(fuzz.ratio('btechgeeks', 'btech geeks'))

print(fuzz.ratio('Hello this is btechgeeks', 'Hello btechgeeks'))

print(fuzz.ratio('Hello this is btechgeeks', 'Welcome'))

Output:

100
95
80
26

Method #2: Using Fuzz.partial_ratio()

Another useful method in the fuzzywuzzy library is partial_ratio(). It handles complex string comparisons such as substring matching.

Below is the implementation:

# Import fuzz from fuzzywuzzy module using the import keyword
from fuzzywuzzy import fuzz  

# Give the string as static input and store it in a variable.
gvn_str1 = "Hello this is btechgeeks"  
# Give the string as static input and store it in a variable.
gvn_str2 = "techgeeks"  

# Check if both the given strings are similar using the fuzz.partial_ratio() function
# by passing given both strings as arguments to it.
# Here it returns a score out of 100, which indicates how much percent 
# they are similar out of 100.
print(fuzz.partial_ratio(gvn_str1, gvn_str2))
  
# Similarly check with other strings and print the result
# Here only the Exclamation mark differs in comparision to both the strings, 
# but partially words are same hence returns 100
print(fuzz.partial_ratio('btechgeeks', 'btechgeeks!'))

print(fuzz.partial_ratio('btechgeeks', 'btech geeks'))

print(fuzz.partial_ratio('Hello this is btechgeeks', 'this is'))

# only partial tokens matches here hence returns 55
print(fuzz.partial_ratio('Hello this is btechgeeks', 'this python'))

Output:

100
100
90
100
55

Method #3: Using Fuzz.token_sort_ratio()

This method does not guarantee an accurate result because we can change the order of the strings. It might not produce an accurate result.

However, the fuzzywuzzy module provides a solution.

Below is the implementation:

# Import fuzz from fuzzywuzzy module using the import keyword
from fuzzywuzzy import fuzz  

# Give the string as static input and store it in a variable.
gvn_str1 = "Hello this is btechgeeks"  
# Give the string as static input and store it in a variable.
gvn_str2 = "this btechgeeks hello is"  

# Check if both the given strings are similar using the fuzz.token_sort_ratio() function
# by passing given both strings as arguments to it.
# Here both the strings are similar but differ in their order of string. 
# Hence it returns 100
print(fuzz.token_sort_ratio(gvn_str1, gvn_str2))

# Similarly check with the other strings and print the result
print(fuzz.token_sort_ratio("Hello this btechgeeks", "Hello this this btechgeeks"))

# Here it returns 100 since the duplicate words are treated as a single word
# by the token_set_ratio() function
print(fuzz.token_set_ratio("Hello this btechgeeks", "Hello this this btechgeeks"))

Output:

100
89
100

Explanation:

Here, we used another method called fuzz.token_set_ratio(), which performs a set operation, extracts the common token, and then performs a ratio() pairwise comparison.

Since the substring or smaller string is made up of larger chunks of the original string or the remaining token is closer to each other, the intersection of the sorted token is always the same.

Method #4: Using process module

If we have a list of options and want to find the closest match/matches we can use the process module to do so.

Below is the implementation:

# Import process module from fuzzywuzzy module using the import keyword
from fuzzywuzzy import process  

# Give the string as static input and store it in a variable.
gvn_string = "Hello betchgeeks"  

# Give the list of options and store it in another variable
gvn_options = ["hello","Hello python","betchgeeks","Python betchgeeks"]  
# Extract the ratios by passing the given string and options to extract() function
ratios_rslt = process.extract(gvn_string, gvn_options)  
print(ratios_rslt)  
# We can choose the string that has highest matching percentage using extractOne() function
most_accurate = process.extractOne(gvn_string, gvn_options)  
print('Most Accurate Result:',most_accurate)

Output:

[('hello', 90), ('betchgeeks', 90), ('Python betchgeeks', 79), ('Hello python', 57)]
Most Accurate Result: ('hello', 90)

Method #5: Using Fuzz.WRatio()

The process module also includes the WRatio, which produces a more accurate result than the simple ratio. It handles lower and upper case, as well as some other parameters.

Below is the implementation:

# Import process module from fuzzywuzzy module using the import keyword
from fuzzywuzzy import process  

# Pass two strings as arguments to the WRatio() function of fuzz module
# to compare both the strings and returns the score
# Here both the strings are similar but differ in their cases(lower/upper)
# The WRatio() function is ignores case-sensitivity, so it returns 100
print(fuzz.WRatio('hello betchgeeks', 'Hello Betchgeeks'))

# Smilarly check for the other strings and print the result
print(fuzz.WRatio('hello betchgeeks', 'hello betchgeeks!!!!'))

# Here we are using the fuzz.ratio() function for the same strings as above
print(fuzz.ratio('hello betchgeeks', 'hello betchgeeks!!!!'))

Output:

100
100
89

FuzzyWuzzy Python library Read More »

How to Get the substring from given string using list slicing in Python?

A substring is a portion of a string. There are several methods in Python for creating a substring and checking if a substring exists in a string, the index of a substring, and more. Let’s take a look at some substring operations.

Slicing

You can extract a substring from a string by slicing with indices that correspond to your substring.

Syntax:

gvn_string[start:stop:step]

Parameters

  • start: Slicing begins at this index of the list.
  • stop: The index of the list at which slicing ends.
  • step: It allows you to select the nth item from start to stop. A number indicating the step of slicing.  The default value is 1.

Python Program to Get the substring from a given string using list slicing

Method #1: Slicing with start and stop values

Approach:

  • Give the string as static input and store it in a variable.
  • Print the given string
  • Create a substring from the start of the string till the required index you want
  • Create a substring from the end of the string
  • Print the substring from the start of the string using slicing.
  • Here printing characters from 0 to 2(excluding the last index).
  • Print the substring from the end of the string using slicing
  • Here printing characters from 4 to the entire string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'hellothisispythonprograms'

# Print the given string 
print("The given string = ", gvn_str)

# create a substring from the start of string till the required index you want 
substr_frm_start = gvn_str[:3]
# create a substring from the end of string 
substr_frm_end = gvn_str[4:]

# Print the substring from the starting of the string using slicing
# here printing charcters from 0 to 2(excluding the last index) 
print("The substring from the starting of the string = ", substr_frm_start)
# Print the substring from the end of the string using slicing
# here printing characters from 4 to entire string
print("The substring from the end of the string = ", substr_frm_end)

Output:

The given string = hellothisispythonprograms
The substring from the starting of the string = hel
The substring from the end of the string = othisispythonprograms

Method #2: Slicing with a step value

Approach:

  • Give the string as static input and store it in a variable.
  • Print the given string
  • Get the substring by taking step value as 3 to the slicing
  • Get the alternative character substring by taking step value as 2
  • Print the substring from the start of the given string with 3 step
  • Print the substring from the given string with alternate characters(step=2).
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'hellothisispythonprograms'
# Print the given string 
print("The given string = ", gvn_str)

# Get the substring by taking step value as 3 to the slicing
substr_withstep3 = gvn_str[::3]
# Get the alternative character substring by taking step value as 2
substr_withstep2 = gvn_str[::2]

# print the substring from the start of the given string with 3 step
print("The substring from the start of the given string with 3 step = ", substr_withstep3)
# print the substring from the given string with alternate characters(step=2)
print("The substring from the given string with alternate characters(step=2)= ", substr_withstep2)

Output:

The given string = hellothisispythonprograms
The substring from the start of the given string with 3 step = hlhiyorrs
The substring from the given string with alternate characters(step=2)= hlohssyhnrgas

Method #3: Slicing with start, stop and step values

Approach:

  • Give the string as static input and store it in a variable.
  • Print the given string
  • Slice from 2nd index to 7 index with alternate characters(because we used step value as 2)
  • Print the resulting substring.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'hellothisispythonprograms'

# Print the given string 
print("The given string = ", gvn_str)

# Slice from 2nd index to 7 index with alternate characters(because we used step value as 2)
sub_string = gvn_str[2:7:2]

# Print the result substring 
print ("The result substring = ", sub_string)

Output:

The given string = hellothisispythonprograms
The result substring = loh

Method #4: Slicing with start, stop and step values (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Print the given string
  • Give the start value as user input using the int(), input() functions and store it in another variable (here int() converts to an integer datatype)
  • Give the end value as user input using the int(), input() functions and store it in another variable
  • Give the step value as user input using the int(), input() functions
    and store it in another variable
  • Slice the given string based on the above-given start, end and step values and store it in another variable
  • Print the resulting substring.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Give some random string = ")

# Print the given string 
print("The given string = ", gvn_str)

# Give the start value as user input using the int(), input() functions
# and store it in another variable (here int() converts to an integer datatype)
gvn_startval = int(input("Give some random start value = "))
# Give the end value as user input using the int(), input() functions
# and store it in another variable 
gvn_endval = int(input("Give some random end value = "))
# Give the step value as user input using the int(), input() functions
# and store it in another variable 
gvn_step = int(input("Give some random step value = "))

# Slice the given string based on the above given start, end and step values  
# and store it in another variable 
sub_string = gvn_str[gvn_startval:gvn_endval:gvn_step]

# Print the result substring 
print ("The result substring = ", sub_string)

Output:

Give some random string = good morning python programs
The given string = good morning python programs
Give some random start value = 1
Give some random end value = 15
Give some random step value = 2
The result substring = odmrigp

Explanation:

Here the string "good morning python programs" is sliced from the 
start index=1(o) to the end index 15(t) with a step value =2 i.e, 
it prints alternative characters

Method #5: Slicing with a step value (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Print the given string
  • Give the step value as user input using the int(), and input() functions and store it in another variable (here int() function converts to an integer datatype).
  • Get the substring by taking the given step value to perform slicing.
  • Print the substring from the input string based on the given step value.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Give some random string = ")
# Print the given string 
print("The given string = ", gvn_str)

# Give the step value as user input using the int(), input() functions
# and store it in another variable (here int() function converts to an integer datatype)
gvn_step = int(input("Give some random step value = "))

# Get the substring by taking the given step value to perform slicing
substr_withstep = gvn_str[::gvn_step]

# print the substring from the input string based on the given step value 
print("The substring from the input string based on the given step value  = ", substr_withstep)

Output:

Give some random string = hellothisispythonprograms
The given string = hellothisispythonprograms
Give some random step value = 2
The substring from the input string based on the given step value = hlohssyhnrgas

How to Get the substring from given string using list slicing in Python? Read More »

Switch Case in Python (Replacement)

Switch case statements

The if statement decides whether or not the condition is true. If the condition is true, the indented expression is evaluated; however, if the condition is false, the indented expression under else is evaluated. When we need to run multiple conditions, we can put as many elif conditions as we need between the if and else conditions. Long if statements that compare a variable to several integral values are replaced by switch case statements.

Switch case statements are a replacement for long if statements that compare a variable to several integral values.

  • The switch statement is a multiway branch statement.
  • It allows you to easily route execution to different parts of code based on the value of the expression.
  • A switch statement is a control statement that allows a value to change execution control.

The following are the benefits of using the Switch Case Statement in the program:

  • It is simpler to debug.
  • Anyone other than the programmer can read the program more easily.
  • It is simpler to understand and also to maintain.
  • It is easier to ensure that all values to be checked are handled.

Replacement of switch case statements in python

Python, unlike any other programming language we’ve used before, lacks a switch or case statement.

In this article let us look at the different methods to implement switch case statements in python:

  • Using dictionary Mapping
  • Using if-else statements
  • Using Classes

Switch Case in Python (Replacement)

Below are the ways to perform switch case in Python:

Method #1: Using Classes

Along with the methods described above for implementing the switch case statement in Python, we can also use Python classes.

A class is an object constructor that has properties and methods. Here we look at the below code of using a class to perform a switch case by creating a switch method within the Python switch class.

Approach:

  • Create a class say SwitchMonths
  • Create a function say month which accepts the month number as an argument
  • Give the default value to print if all the conditions fail
  • Get the attribute value by converting the month number to a string and concatenating with case_ (example case_3)
  • Create functions inside the class for each month
  • Create an object for the above SwitchMonths() class and store it in a variable
  • Call the month() function inside the class using the above object by passing the switch case number(month number) as an argument to it
  • Similarly, do the same for others.
  • The Exit of the Program.

Below is the implementation:

# Create a class say SwitchMonths
class SwitchMonths:
    # Create a function say month which accepts the month number as an argument
    def month(self, month):
        # Give the default value to print if all the conditions fails
        default = "Invalid Month"
        # get the attribute value by converting month number to string and concatenating with case_ (example case_3)
        return getattr(self, 'case_' + str(month), lambda: default)()
    # Create functions inside class for each month
    def case_1(self):
        return "january"

    def case_2(self):
        return "febrauary"

    def case_3(self):
        return "march"

    def case_4(self):
       return "april"

    def case_5(self):
        return "may"

    def case_6(self):
        return "june"
    
    def case_7(self):
        return "july"

    def case_8(self):
        return "august"

# Create an object for the above SwitchMonths() class and store it in a variable
class_object = SwitchMonths()

# Call the month() function inside the class using the above 
# object by passing the switch case number(month number) as an argumet to it
print ("The 4th month is:", class_object.month(4))
# Similarly do the same for other
print ("The 7th month is:", class_object.month(7))

Output:

The 4th month is: april
The 7th month is: july

Method #2: Using if-else statements

If-elif is a shortcut for the if-else chain. We can use the if-elif statement and add an else statement at the end to perform if none of the if-elif statements above are true.

Syntax:

if (condition):
    statement
elif (condition):
    statement
.
.
else:
    statement

Approach:

  • Give the string(website name) as static input and store it in a variable.
  • Check if the given website name is Btechgeeks using the if conditional statement and == operator.
  • If it is true, the print “The given website is Btechgeeks”.
  • Else Again Check if the given website name is Sheetstips using the elif conditional statement
    and == operator.
  • If it is true, the print “The given website is Sheetstips”.
  • Else Again Check if the given website name is PythonPrograms using the elif conditional statement
    and == operator.
  • If it is true, the print “The given website is PythonPrograms”.
  • Else if all the above conditions fail then print some random acknowledgment.
    in an else conditional statement at the end.
  • The Exit of the Program.

Below is the implementation:

# Give the string(website name) as static input and store it in a variable.
gvn_website = 'PythonPrograms'

# Check if the given website name is Btechgeeks using the if conditional statement
# and == operator.
if gvn_website == 'Btechgeeks': 
    # If it is true, the print "The given website is Btechgeeks".
    print("The given website is Btechgeeks") 

# Else Again Check if the given website name is Sheetstips using the elif conditional statement
# and == operator.
elif gvn_website == "Sheetstips": 
    # If it is true, the print "The given website is Sheetstips".
    print("The given website is Sheetstips") 

# Else Again Check if the given website name is PythonPrograms using the elif conditional statement
# and == operator.
elif gvn_website == "PythonPrograms": 
    # If it is true, the print "The given website is PythonPrograms".
    print("The given website is PythonPrograms") 

# Else if all the above conditions fails then print some random acknowledgement 
# in a else conditional statement at the end
else: 
    print("Sorry! It is not a correct website")

Output:

The given website is PythonPrograms

Method #3: Using dictionary Mapping

The dictionary in Python uses key-value pairs to store groups of objects in memory. The key value of the dictionary data type acts as a ‘case’ in a switch case statement when implementing the switch case statement.

Below is the implementation:

def january():
    return "january"
def febrauary():
    return "febrauary"
def march():
    return "march"
def april():
    return "april"
def may():
    return "may"
def june():
    return "june"
def july():
    return "july"
def august():
    return "august"
def september():
    return "september"
def october():
    return "october"
def november():
    return "november"
def december():
    return "december"
def default():
    return "Invalid Month"
# Dictionary to store month values/numbers
switcherDict = {
    1: january,
    2: febrauary,
    3: march,
    4: april,
    5: may,
    6: june,
    7: july,
    8: august,
    9: september,
    10: october,
    11:november,
    12:december
    }

def switch(month): 
    return switcherDict.get(month, default)()

# Passing the value of the month to the switch() function to get month name
print("The 5th month is:", switch(5))
print("The 8th month is:", switch(8))

Output:

The 5th month is: may
The 8th month is: august

 

Switch Case in Python (Replacement) Read More »

12 Python In-Built Functions You Should Know

In this article, let us look at the 12 important in-built Functions in Python which helps you to code quickly and easily.

1)append()

The append() function in Python takes a single item as input and appends it to the end of the given list, tuple, or any other set. In Python, append() does not return a new list of items; instead, it returns null. It simply modifies the original list by adding the item at the end.

The length of the list is then increased by one. We can add an item to the list and also add a list to another list. It adds any data type that should be at the end of the list.

Time complexity: O(1).

Syntax:

append(item)

Parameters

  • item: It is the item that is to be added/appended

Example

# Give the list as static input and store it in a variable.
gvn_lst = ["Hello", "this", "is"]

# Pass some random string element as an argument to the append() function 
# and apply it on the given list to add the element at the end of the list
gvn_lst.append("PythonPrograms")

# Print the given list after appending a new list element at the end
print(gvn_lst)

Output:

['Hello', 'this', 'is', 'PythonPrograms']

2)reduce()

The reduce() function in Python iterates through each item in a list or other iterable data type and returns a single value. It is found in the functools library. This is more effective than loop.

Syntax:

reduce(function, iterable)

Parameters

  • function: The function that will be used in the code
  • iterable: The value that will be iterated in the code

Example

# Import reduce() function from functools module using the import keyword
from functools import reduce
def multiply(x, y):
   return x*y
gvn_lst = [2, 3, 5]
print(reduce(multiply, gvn_lst))

Output:

30

3)split():

The split() function is used to split a string into a list of strings by breaking it with the specified separator. The separator can be specified; the default separator is any whitespace.

Syntax:

str.split(separator, maxsplit)

Parameters

  • separator: This is optional. The delimiter at which splits occur. If no separator is specified, the string is split at whitespaces.
  • maxsplit: This is optional. It is the maximum number of splits. There is no limit to the number of splits if it is not provided.

Return Value:

A list of strings is returned by the split() function.

Example

# Give the first string as static input and store it in a variable.
gvn_str1= 'Hello this is pythonprograms'
# Apply split() function on the given first string without 
# passing any separator as an argument
# Here it splits the given string based on the whitespaces by default
print("Splitting gvn_str1:", gvn_str1.split())

# Give the second string as static input and store it in another variable.
gvn_str2 = 'Hello,this,is pythonprograms'

# Apply split() function on the given second string by passing any separator as (,) and maxsplit=1  
# as arguments to it 
# Here it splits the given string containing commas.
# Here 1 specifies we are going to split the first comma as separate element
print("Splitting gvn_str2:", gvn_str2.split(',', 1))

Output:

Splitting gvn_str1: ['Hello', 'this', 'is', 'pythonprograms']
Splitting gvn_str2: ['Hello', 'this,is pythonprograms']

4)Slice():

Based on the specified range, the slice() method returns a portion of an iterable as an object of the slice class. It works with string, list, tuple, set, bytes, or range objects, as well as custom class objects that implement the sequence methods, __getitem__() and __len__().

Syntax:

slice(stop)
slice(start, stop, step)

Parameters

  • start: This is optional. The index at which the iterable’s slicing starts. None is the default value
  • stop: This is the ending index of slicing.
  • step: This is optional. It is the number of steps to jump/increment.

Example

# Give the list as static input and store it in a variable.
gvn_list = [1, 3, 6, 8, 9, 4, 10, 14, 18]


# Pass start, stop as arguments to the slice() function to get the part of the list
# (default stepsize is 1) and store it in a variable.
# Here it returns the list elements in the index range 2 to 6(excluding the last index)
sliceObject_1 = slice(2, 7)

# Pass only the stop value as an argument to the slice() function 
# to get the portion of the list in the given range
# Here start and step values are considered 0, 1 respectively bu default and 
# we get a list elements in the index range 0 to 4
sliceObject_2 = slice(5)

# Slice the given list by passing the start, stop, step values as arguments
# to the slice() function and store it in a variable.
# Here it returnslist elements from index 1 to 7(excluding last index) with the step value 2 
sliceObject_3 = slice(1, 8, 2)
 
# Print the result list elements in the index range 2 to 6
print("The result list elements in the index range 2 to 6: ", gvn_list[sliceObject_1]) 
# Print the result list elements in the index range 0 to 4
print("The result list elements in the index range 0 to 4: ", gvn_list[sliceObject_2])
# Print the result list elements in the index range 1 to 7 with step=2
print("The result list elements in the index range 1 to 7 with step=2: ", gvn_list[sliceObject_3])

Output:

The result list elements in the index range 2 to 6: [6, 8, 9, 4, 10]
The result list elements in the index range 0 to 4: [1, 3, 6, 8, 9]
The result list elements in the index range 1 to 7 with step=2: [3, 8, 4, 14]

5)eval()

The eval() function in Python allows you to perform mathematical operations on integers or floats, even in string form. A mathematical calculation in string format is frequently useful.

The eval() function evaluates the given expression(mathematical or logical). It parses the function, compiles it to bytecode, and then returns the output if a string is passed to it. Because operators have no time complexity, neither does eval.

Syntax:

eval(expression)

Parameters

  • expression: It could be any expression either mathematical or logical

Example

# Give the number as static input and store it in a variable.
gvn_num = 8

# Evaluate the given expression using the eval() function and 
# store it in another variable.
rslt= eval("(gvn_num *9)/2")

# Print the result
print(rslt)

Output:

36.0

6)map()

The map() function, like reduce(), allows you to iterate over each item in an iterable. Map(), on the other hand, operates on each item independently, rather than producing a single result.

Finally, you can use the map() function to perform mathematical operations on two or more lists. It can even be used to manipulate an array of any data type.

Time complexity of the map() = O(n)

Syntax:

map(function, iterable)

Parameters

  • function: The function that will be used in the code
  • iterable: The value that will be iterated in the code
# Create a function which accepts the number as argument and 
# returns the addition of that number with 5 as a result
def add_numbers(gvn_num):
   # Add 5 to the given number and return the result
   return gvn_num+5

# Pass the above add_numbers function and tuple of numbers as arguments to the 
# map() function 
# It will apply the add_numbers function for every element of the list
gvn_num = map(add_numbers, (2, 5, 10, 16))
# Print the result
print(*gvn_num)

Output:

7 10 15 21

7)bin()

The bin() function converts an integer to a binary string prefixing with 0b. Moreover, the integer passed may be negative or positive. For a number n, the time complexity is O(log(n)).

Syntax:

bin(integer)

Parameters

  • integer: It is an integer value passed in order to obtain its binary form.

Example

# Print the binary value of any number by passing it as an argument to the bin() function
# Here we are printing the binary value of 7
print("Binary value of 7 = ", bin(7))

# Here we are printing the binary value of 5
print("Binary value of 5 = ", bin(5))

Output:

Binary value of 7 = 0b111
Binary value of 5 = 0b101

8)enumerate()

The enumerate() function returns the length of an iterable while simultaneously looping through its items. As a result, while printing each item in an iterable data type, it also prints its index.

Assume you want a user to see a list of the items in your database. You can put them in a list and use the enumerate() function to get a numbered list out of it.

Example1

# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "pythonprograms"]

# Loop in the given list with first iterator(i) as index and second iterator as list element value
for i, j in enumerate(gvn_lst):
    print(i, j)

Output:

0 hello
1 this
2 is
3 pythonprograms

Enumerating the list, in addition to being faster, allows you to customize how your numbered items appear.

In fact, by including a start parameter, you can choose to begin numbering from the number you want rather than zero.

Example2

# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "pythonprograms"]

# Pass the given list, start value(from where you want to begin the index number) 
# as arguments to the enumerate() function 
for i, j in enumerate(gvn_lst, start=5):
    print(i, j)

Output:

5 hello
6 this
7 is
8 pythonprograms

9)filter()

The filter() function creates a new iterator that filters elements from an existing one (like list, tuple, or dictionary).

It checks whether the given condition is present in the sequence or not and then prints the result.

Time complexity = O(n).

Syntax:

filter(function, iterable)

Parameters

  • function: The function that will be used in the code
  • iterable: The value that will be iterated in the code
# Give the list as static input and store it in a variable.
gvn_lst = ["hello", "this", "is", "pythonprograms"]
 
   
def vowels(x):
  # Checking whether the first character is vowel
  return x[0].lower() in 'aeiou'

elements = filter(vowels, gvn_lst)

print(list(elements))

Output:

['is']

10)strip()

Strip() in Python removes leading characters from a string. It removes the first character from the string repeatedly if it matches any of the provided characters.

If no character is specified, the strip removes all leading whitespace characters from the string.

# Give the string as static input and store it in a variable.
gvn_str = "pythonprograms"
# Pass a charcter to be stripped/removed from a given as an argument
# to the strip() function and print the result.
# Here it removes/strips the first p character from the given string
rslt = gvn_str.strip("p")
print(rslt)

Output:

ythonprograms

11)exec()

The exec() function executes the specified condition and returns the result in Python expression form.

The Python exec() function runs a dynamically created program, which can be a string or a code object. If it is a string, it is parsed as a Python statement and executed; otherwise, a syntax error is produced.

Syntax:

exec(object[, globals[, locals]])

Parameters

  • object: It could be a string or object code.
  • globals: This is optional. It could be a dictionary.
  • locals: This is optional. It could be a mapping object.

Example

# Give the number as static input and store it in a variable.
gvn_num = 5
# Multiply the given number with 10 and pass it as a string to the exec()
# function to execute the given condition
exec('print(gvn_num*10)')

Output:

50

12)sorted()

The sorted() function returns a sorted list of the given iterable object.

You can sort either in ascending or descending order by specifying it. Numbers are sorted numerically, while strings are sorted alphabetically.

Syntax:

sorted(iterable, key=key, reverse=False)

Parameters

  • iterable: This is required. It could be any sequence to be sorted like list, dictionary, tuple, etc.
  • key: This is optional. It is a function to execute to decide the order. None is the default value.
  • reverse: This is optional. A Boolean expression. True sorts in ascending, False sorts in descending order. The default value is False.

Example1: Sorting the given list of strings in ascending order

# Give the list of strings as static input and store it in a variable.
gvn_lst = ["r", "c", "e", "h", "v", "s"]

# Pass the given list as an argument to the sorted() function to sort the 
# given list in ascending order alphabetically. 
sorted_lst = sorted(gvn_lst)
# Print the given list after sorting
print("The given list after sorting = ", sorted_lst)

Output:

The given list after sorting = ['c', 'e', 'h', 'r', 's', 'v']

Example2: Sorting the given list of strings in descending order

# Give the list of strings as static input and store it in a variable.
gvn_lst = ["r", "c", "e", "h", "v", "s"]

# Pass the given list, reverse=True as arguments to the sorted() function to sort the 
# given list in descending order alphabetically. 
sorted_lst = sorted(gvn_lst, reverse=True)
# Print the given list after sorting in descending order
print("The given list after sorting in descending order = ", sorted_lst)

Output:

The given list after sorting in descending order = ['v', 's', 'r', 'h', 'e', 'c']

Example3: Sorting the given list of numbers in descending order

# Give the list of numbers as static input and store it in a variable.
gvn_lst = [1, 34, 6, 10, 2, 25, 80]

# Pass the given list, reverse=True as arguments to the sorted() function to sort the 
# given list of numbers in descending order. 
sorted_lst = sorted(gvn_lst, reverse=True)
# Print the given list after sorting in descending order
print("The given list after sorting in descending order = ", sorted_lst)

Output:

The given list after sorting in descending order = [80, 34, 25, 10, 6, 2, 1]

12 Python In-Built Functions You Should Know Read More »