Python

Program to Group Words with the Same Set of Characters

Python Program to Group Words with the Same Set of Characters

Group Words:

In Python, grouping words with the same set of characters is also known as Group Anagrams. We are given a list of words with the same set of characters but in various positions in the word, such as ‘clock’ and ‘klocc’ and we must group them together in a list.

Given the list of words, the task is to group words with the Same set of Characters.

Examples:

Example1:

Input:

Given list of strings = ['ehlo', 'this', 'is', 'olhe', 'helo', 'si', 'btechgeeks']

Output:

The group of words which are similar in given list of strings  ['ehlo', 'this', 'is', 'olhe', 'helo', 'si', 'btechgeeks'] is :
[['ehlo', 'olhe', 'helo'], ['this'], ['is', 'si'], ['btechgeeks']]

Example2:

Input:

Given list of strings = ['here', 'we', 'are', 'ew', 'in', 'galazy', 'ereh', 'aer']

Output:

The group of words which are similar in given list of strings ['here', 'we', 'are', 'ew', 'in', 'galazy', 'ereh', 'aer'] is :
[['here', 'ereh'], ['we', 'ew'], ['are', 'aer'], ['in'], ['galazy']]

Program to Group Words with the Same Set of Characters in Python

Below are the ways to group words with the same set of characters in Python.

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Method #1: Using For Loop (Static Input)

Approach:

  • Import the defaultdict from collections using the import keyword.
  • Give the list of strings as static input and store it in a variable.
  • The defaultdict method is used to construct a dictionary corresponding to a key that contains word characters.
  • The list argument is used to generate key-value list pairs.
  • Loop over the list of strings using For loop.
  • The str method on sorted(word) returns a list of keys that include the alphabets of words.
  • Append the word using append(word) joins together words that are related.
  • Get all the values of the defaultdict using the values() function.
  • Print the defaultdict.
  • The Exit of the Program.

Below is the implementation:

# Import the defaultdict from collections using the import keyword.

from collections import defaultdict
# Give the list of strings as static input and store it in a variable.
gvnstrnglist = ['ehlo', 'this', 'is', 'olhe', 'helo', 'si', 'btechgeeks']
# The defaultdict method is used to construct a dictionary
# corresponding to a key that contains word characters.
# The list argument is used to generate key-value list pairs.
grpwords = defaultdict(list)

# Loop over the list of strings using For loop.
for strngword in gvnstrnglist:
    # The str method on sorted(word) returns a list of keys
    # that include the alphabets of words.
    # Append the word using append(word) joins together words that are related.
    grpwords[str(sorted(strngword))].append(strngword)

# Get all the values of the defaultdict using the values() function.
simipairs = list(grpwords.values())
# Print the defaultdict.
print('The group of words which are similar in given list of strings ',
      gvnstrnglist, 'is :')
print(simipairs)

Output:

The group of words which are similar in given list of strings  ['ehlo', 'this', 'is', 'olhe', 'helo', 'si', 'btechgeeks'] is :
[['ehlo', 'olhe', 'helo'], ['this'], ['is', 'si'], ['btechgeeks']]

Method #2: Using For Loop (User Input)

Approach:

  • Import the defaultdict from collections using the import keyword.
  • Give the list of strings as user input using list(), split(), and input() functions and store it in a variable.
  • The defaultdict method is used to construct a dictionary corresponding to a key that contains word characters.
  • The list argument is used to generate key-value list pairs.
  • Loop over the list of strings using For loop.
  • The str method on sorted(word) returns a list of keys that include the alphabets of words.
  • Append the word using append(word) joins together words that are related.
  • Get all the values of the defaultdict using the values() function.
  • Print the defaultdict.
  • The Exit of the Program.

Below is the implementation:

# Import the defaultdict from collections using the import keyword.

from collections import defaultdict
# Give the list of strings as user input using list(), split(), and input() functions
# and store it in a variable.
gvnstrnglist = list(input('Enter some random list of strings = ').split())
# The defaultdict method is used to construct a dictionary
# corresponding to a key that contains word characters.
# The list argument is used to generate key-value list pairs.
grpwords = defaultdict(list)

# Loop over the list of strings using For loop.
for strngword in gvnstrnglist:
    # The str method on sorted(word) returns a list of keys
    # that include the alphabets of words.
    # Append the word using append(word) joins together words that are related.
    grpwords[str(sorted(strngword))].append(strngword)

# Get all the values of the defaultdict using the values() function.
simipairs = list(grpwords.values())
# Print the defaultdict.
print('The group of words which are similar in given list of strings ',
      gvnstrnglist, 'is :')
print(simipairs)

Output:

Enter some random list of strings = here we are ew in galazy ereh aer
The group of words which are similar in given list of strings ['here', 'we', 'are', 'ew', 'in', 'galazy', 'ereh', 'aer'] is :
[['here', 'ereh'], ['we', 'ew'], ['are', 'aer'], ['in'], ['galazy']]

Related Programs:

Python Program to Group Words with the Same Set of Characters Read More »

Program to Create a List of Tuples with the First Element as the Number and Second Element as the Square of the Number

Python Program to Create a List of Tuples with the First Element as the Number and Second Element as the Square of the Number

Tuples in Python:

Tuples are comma-separated sequences or collections of things. In many aspects, they are identical to lists, except that the elements cannot be modified after they are created. Tuples in Python, unlike lists, are immutable objects. They also employ parentheses rather than square brackets.

Lists in Python:

A list is exactly what it sounds like: a container for various Python objects such as integers, words, values, and so on. In other programming languages, it is equal to an array. It is denoted with square brackets (and this is one of the attributes that differentiates it from tuples, which are separated by parentheses). It is also mutable, which means it can be changed or altered, as opposed to tuples, which are immutable.

Given lower limit range and upper limit range the task is to Make a list of Tuples with the first element being the number and the second element being the square of the number.

Examples:

Example1:

Input:

Enter some random lower limit =5
Enter some random lower limit =13

Output:

The list of Tuples are :  [(5, 25), (6, 36), (7, 49), (8, 64), (9, 81), (10, 100), (11, 121), (12, 144), (13, 169)]

Example2:

Input:

Enter some random lower limit =23
Enter some random lower limit =69

Output:

The list of Tuples are :  [(23, 529), (24, 576), (25, 625), (26, 676), (27, 729), (28, 784), (29, 841), (30, 900), (31, 961), 
(32, 1024), (33, 1089), (34, 1156), (35, 1225), (36, 1296), (37, 1369), (38, 1444), (39, 1521), (40, 1600), (41, 1681), 
(42, 1764), (43, 1849), (44, 1936), (45, 2025), (46, 2116), (47, 2209), (48, 2304), (49, 2401), (50, 2500), (51, 2601),
(52, 2704), (53, 2809), (54, 2916), (55, 3025), (56, 3136), (57, 3249), (58, 3364), (59, 3481), (60, 3600), (61, 3721),
(62, 3844), (63, 3969), (64, 4096), (65, 4225), (66, 4356), (67, 4489), (68, 4624), (69, 4761)]

Make a list of Tuples with the first element being the number and the second element being the square of the number in Python

There are several ways to create a list of tuples with the first element being the number and the second element being square of the given number some of them are:

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Method 1:Using list comprehension (Static input)

Approach:

  • Give the lower limit range and upper limit range as static input.
  • Using list comprehension, generate a list of tuples with the first element being the number within the range and the second element being the square of the number.
  • The list of tuples will be printed.
  • Exit of program.

Below is the implementation:

# given lower limit range as static input
lowerlimit = 5
# given upper limit range as static input
upperlimit = 13
# Using list comprehension, generate a list of tuples with the first element being the number within
# the range and the second element being the square of the number.
listOfTuples = [(k, k**2) for k in range(lowerlimit, upperlimit+1)]
# printing the list of tuples
print('The list of Tuples are : ', listOfTuples)

Output:

The list of Tuples are :  [(5, 25), (6, 36), (7, 49), (8, 64), (9, 81), (10, 100), (11, 121), (12, 144), (13, 169)]

Explanation:

List comprehension must be used to produce a list of tuples in which the first element is the supplied range’s number and the second element is a square of the first number.

Method 2:Using list comprehension (User input)

Approach:

  • Scan the lower limit range and upper limit range as user input using int(input()) which converts string to integer.
  • Using list comprehension, generate a list of tuples with the first element being the number within the range and the second element being the square of the number.
  • The list of tuples will be printed.
  • Exit of program.

Below is the implementation:

# Scan lower limit range as user input
lowerlimit = int(input("Enter some random lower limit ="))
# Scan upper limit range as user  input
upperlimit = int(input("Enter some random lower limit ="))
# Using list comprehension, generate a list of tuples with the first element being the number within
# the range and the second element being the square of the number.
listOfTuples = [(k, k**2) for k in range(lowerlimit, upperlimit+1)]
# printing the list of tuples
print('The list of Tuples are : ', listOfTuples)

Output:

Enter some random lower limit =11
Enter some random lower limit =49
The list of Tuples are : [(11, 121), (12, 144), (13, 169), (14, 196), (15, 225), (16, 256), (17, 289), (18, 324), (19, 361), 
(20, 400), (21, 441), (22, 484), (23, 529), (24, 576), (25, 625), (26, 676), (27, 729), (28, 784), (29, 841), (30, 900), (31, 961),
 (32, 1024), (33, 1089), (34, 1156), (35, 1225), (36, 1296), (37, 1369), (38, 1444), (39, 1521), (40, 1600), (41, 1681), 
(42, 1764), (43, 1849), (44, 1936), (45, 2025), (46, 2116), (47, 2209), (48, 2304), (49, 2401)]

Method 3:Using for loop and append() function (Static input)

Approach:

  • Give the lower limit range and upper limit range as static input.
  • Take a empty list.
  • Iterate from lower limit range to upper limit range using for loop
  • Add iterate value and square of iterator value to the list as tuple using append() function.
  • The list of tuples will be printed.
  • Exit of program.

Below is the implementation:

# given lower limit range as static input
lowerlimit = 23
# given upper limit range as static input
upperlimit = 69
# Taking a empty list
listOfTuples = []
# using for loop
for value in range(lowerlimit, upperlimit+1):
    # adding number and square of the iterator value
    listOfTuples.append((value, value**2))

listOfTuples = [(k, k**2) for k in range(lowerlimit, upperlimit+1)]
# printing the list of tuples
print('The list of Tuples are : ', listOfTuples)

Output:

The list of Tuples are :  [(23, 529), (24, 576), (25, 625), (26, 676), (27, 729), (28, 784), (29, 841), (30, 900), (31, 961), 
(32, 1024), (33, 1089), (34, 1156), (35, 1225), (36, 1296), (37, 1369), (38, 1444), (39, 1521), (40, 1600), (41, 1681), 
(42, 1764), (43, 1849), (44, 1936), (45, 2025), (46, 2116), (47, 2209), (48, 2304), (49, 2401), (50, 2500), (51, 2601),
(52, 2704), (53, 2809), (54, 2916), (55, 3025), (56, 3136), (57, 3249), (58, 3364), (59, 3481), (60, 3600), (61, 3721),
(62, 3844), (63, 3969), (64, 4096), (65, 4225), (66, 4356), (67, 4489), (68, 4624), (69, 4761)]

Related Programs:

Python Program to Create a List of Tuples with the First Element as the Number and Second Element as the Square of the Number Read More »

Python Program to Print each Word of a Sentence along with Number of Vowels in each Word

Python Program to Print each Word of a Sentence along with Number of Vowels in each Word

Given a sentence, the task is to print each word of a Sentence along with the number of vowels in each word.

Examples:

Example1:

Input:

Given word ='Hello this is BTechgeeks'

Output:

The total number of vowels in the given word { hello } is 2
The total number of vowels in the given word { this } is 1
The total number of vowels in the given word { is } is 1
The total number of vowels in the given word { btechgeeks } is 3

Example2:

Input:

Given word = 'good morning this is btechgeeks python coding platform'

Output:

The total number of vowels in the given word { good } is 2
The total number of vowels in the given word { morning } is 2
The total number of vowels in the given word { this } is 1
The total number of vowels in the given word { is } is 1
The total number of vowels in the given word { btechgeeks } is 3
The total number of vowels in the given word { python } is 1
The total number of vowels in the given word { coding } is 2
The total number of vowels in the given word { platform } is 2

Program to Print each Word of a Sentence along with the Number of Vowels in each Word in Python

Below are the ways to print each word of a Sentence along with the number of vowels in each word.

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the sentence as static input and store it in a variable.
  • Convert the given string/sentence to lowercase using the lower() function.
  • To break words from a sentence, use the string.split() method.
  • The words will be separated and kept in a list named ‘stringwords’
  • Create a list called vowelchars, which will hold all of the vowels in the English alphabet.
  • Iterate through the list of words and set up a counter to count the number of vowels in each one.
  • Start a nested loop that iterates throughout the word in question, checking whether any of the characters are vowels.
  • Increase the counter if a character is a vowel.
  • Print the current iteration’s word and the value of the counter corresponding with it (which contains the sentence’s number of vowels).
  • The Exit of the program.

Below is the implementation:

# Give the sentence as static input and store it in a variable.
givnstrng = 'Hello this is BTechgeeks'
# Convert the given string/sentence to lowercase using the lower() function.
givnstrng = givnstrng.lower()
# To break words from a sentence, use the string.split() method.
# The words will be separated and kept in a list named ‘wordslst'
wordslst = givnstrng.split()
# Create a list called vowelchars, which will hold all of the vowels in the English alphabet.
vowelchars = ['a', 'e', 'i', 'o', 'u']
# Iterate through the list of words and set up a counter to count
# the number of vowels in each one.
for gvnword in wordslst:
    cntvowel = 0
    # Start a nested loop that iterates throughout the word in question,
    # checking whether any of the characters are vowels.
    for m in gvnword:
        # Increase the counter if a character is a vowel.
        if m in vowelchars:
            cntvowel = cntvowel+1
    # Print the current iteration's word and the value
    # of the counter corresponding with it
    # (which contains the sentence's number of vowels).
    print(
        'The total number of vowels in the given word {', gvnword, '} is', cntvowel)

Output:

The total number of vowels in the given word { hello } is 2
The total number of vowels in the given word { this } is 1
The total number of vowels in the given word { is } is 1
The total number of vowels in the given word { btechgeeks } is 3

Method #2: Using For Loop (User Input)

Approach:

  • Give the sentence as user input using input() and store it in a variable.
  • Convert the given string/sentence to lowercase using the lower() function.
  • To break words from a sentence, use the string.split() method.
  • The words will be separated and kept in a list named ‘stringwords’
  • Create a list called vowelchars, which will hold all of the vowels in the English alphabet.
  • Iterate through the list of words and set up a counter to count the number of vowels in each one.
  • Start a nested loop that iterates throughout the word in question, checking whether any of the characters are vowels.
  • Increase the counter if a character is a vowel.
  • Print the current iteration’s word and the value of the counter corresponding with it (which contains the sentence’s number of vowels).
  • The Exit of the program.

Below is the implementation:

# Give the sentence as user input using input() and store it in a variable.
givnstrng = input('Enter some random sentence = ')
# Convert the given string/sentence to lowercase using the lower() function.
givnstrng = givnstrng.lower()
# To break words from a sentence, use the string.split() method.
# The words will be separated and kept in a list named ‘wordslst'
wordslst = givnstrng.split()
# Create a list called vowelchars, which will hold all of the vowels in the English alphabet.
vowelchars = ['a', 'e', 'i', 'o', 'u']
# Iterate through the list of words and set up a counter to count
# the number of vowels in each one.
for gvnword in wordslst:
    cntvowel = 0
    # Start a nested loop that iterates throughout the word in question,
    # checking whether any of the characters are vowels.
    for m in gvnword:
        # Increase the counter if a character is a vowel.
        if m in vowelchars:
            cntvowel = cntvowel+1
    # Print the current iteration's word and the value
    # of the counter corresponding with it
    # (which contains the sentence's number of vowels).
    print(
        'The total number of vowels in the given word {', gvnword, '} is', cntvowel)

Output:

Enter some random sentence = good morning this is btechgeeks python coding platform
The total number of vowels in the given word { good } is 2
The total number of vowels in the given word { morning } is 2
The total number of vowels in the given word { this } is 1
The total number of vowels in the given word { is } is 1
The total number of vowels in the given word { btechgeeks } is 3
The total number of vowels in the given word { python } is 1
The total number of vowels in the given word { coding } is 2
The total number of vowels in the given word { platform } is 2

Related Programs:

Python Program to Print each Word of a Sentence along with Number of Vowels in each Word Read More »

Python Program to Create a Countdown Timer

Python Program to Create a Countdown Timer

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

We’ll look at how to make a countdown timer in Python. The code will accept the user’s input on the length of the countdown in seconds. Following that, a countdown in the format ‘minutes: seconds’ will commence on the screen. Here, we’ll make use of the time module.

Python Program to Create a Countdown Timer

Below are the ways to Create a Countdown Timer in Python.

Method #1: Using While Loop (Static Input)

The time module and its sleep() function will be used. To make a countdown timer, follow the steps below:

Approach:

  • Import the time module using the import statement.
  • Then in seconds, Give the length of the countdown as static input and store it in a variable.
  • This value is passed to the user-defined function countdownTime() as a parameter ‘tim’ .
  • A while loop is used in this function until the time reaches zero.
  • To calculate the number of minutes and seconds, use divmod().
  • Now, using the variable timeformat, output the minutes and seconds on the screen.
  • By using end = ‘\n ‘, we force the cursor to return to the beginning of the screen (carriage return), causing the following line written to overwrite the preceding one.
  • The time. sleep() function is used to make the program wait one second.
  • Now decrement time so that the while loop can reach a finish.
  • After the loop is completed, we will print “The Given time is completed” to indicate the conclusion of the countdown.

Below is the implementation:

# Import the time module using the import statement.
import time

# creating a function time which counts the time


def countdownTime(tim):
    # A while loop is used in this function until the time reaches zero.
    while (tim):
       # To calculate the number of minutes and seconds, use divmod(). 
        timemins, timesecs = divmod(tim, 60)
    # Now, using the variable timeformat, output the minutes and seconds on the screen.
        timercount = '{:02d}:{:02d}'.format(timemins, timesecs)
    # By using end = '\n', we force the cursor to return to the
    # beginning of the screen (carriage return),
    # causing the following line written to overwrite the preceding one.
        print(timercount, end="\n")
    # The time. sleep() function is used to make the program wait one second.
        time.sleep(1)
    # Now decrement time so that the while loop can reach a finish.
        tim -= 1
    # After the loop is completed, we will print "The Given time is completed" to indicate the conclusion of the countdown.
    print('The Given time is completed')


# Then in seconds, Give the length of the countdown as static input and store it in a variable.
tim = 5

# Passing the given time as argument to the countdownTime() function
countdownTime(tim)

Output:

00:05
00:04
00:03
00:02
00:01
The Given time is completed

Method #2: Using While Loop (User Input)

The time module and its sleep() function will be used. To make a countdown timer, follow the steps below:

Approach:

  • Import the time module using the import statement.
  • Then in seconds, Give the length of the countdown as user input and store it in a variable.
  • Convert the given time in seconds to integer data type using int() function.
  • This value is passed to the user-defined function countdownTime() as a parameter ‘tim’ .
  • A while loop is used in this function until the time reaches zero.
  • To calculate the number of minutes and seconds, use divmod().
  • Now, using the variable timeformat, output the minutes and seconds on the screen.
  • By using end = ‘\n ‘, we force the cursor to return to the beginning of the screen (carriage return), causing the following line written to overwrite the preceding one.
  • The time. sleep() function is used to make the program wait one second.
  • Now decrement time so that the while loop can reach a finish.
  • After the loop is completed, we will print “The Given time is completed” to indicate the conclusion of the countdown.

Below is the implementation:

# Import the time module using the import statement.
import time

# creating a function time which counts the time


def countdownTime(tim):
    # A while loop is used in this function until the time reaches zero.
    while (tim):
       # To calculate the number of minutes and seconds, use divmod(). 
        timemins, timesecs = divmod(tim, 60)
    # Now, using the variable timeformat, output the minutes and seconds on the screen.
        timercount = '{:02d}:{:02d}'.format(timemins, timesecs)
    # By using end = '\n', we force the cursor to return to the
    # beginning of the screen (carriage return),
    # causing the following line written to overwrite the preceding one.
        print(timercount, end="\n")
    # The time. sleep() function is used to make the program wait one second.
        time.sleep(1)
    # Now decrement time so that the while loop can reach a finish.
        tim -= 1
    # After the loop is completed, we will print "The Given time is completed" to indicate the conclusion of the countdown.
    print('The Given time is completed')


# Then in seconds, Give the length of the countdown as user input and store it in a variable.
tim = input('Enter some random time = ')
# Convert the given time in seconds to integer data type using int() function.
tim = int(tim)

# Passing the given time as argument to the countdownTime() function
countdownTime(tim)

Output:

Enter some random time = 4
00:04
00:03
00:02
00:01
The Given time is completed

Related Programs:

Python Program to Create a Countdown Timer Read More »

Python Program to get the IP Address of your Computer

Python Program to get the IP Address of your Computer

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

In this tutorial, we’ll learn how to construct a Python program to acquire our computer’s IP address.

Before we begin the program, let us learn more about the IP Address.

IP Address:

An IP address (internet protocol address) is a numerical representation that identifies a specific network interface.

IPv4 addresses are 32 bits long. There are a total of 4,294,967,296 (232) unique addresses available. IPv6 addresses are 128 bits long, allowing for a total of 3.4 x 1038 (2128) distinct addresses.

Various reserved addresses and other considerations restrict the overall useable address pool in both versions.

IP addresses are binary numbers, but they’re usually written in decimal (IPv4) or hexadecimal (IPv6) to make them easier to understand and use for people.

The Internet Protocol (IP) is a set of standards and specifications for generating and transferring data packets, or datagrams, across networks. The Internet Protocol (IP) is a component of the Internet protocol suite’s Internet layer. IP is considered part of the network layer in the OSI paradigm. IP is usually used in conjunction with a higher-level protocol, the most common of which being TCP. RFC 791 is the standard that governs the IP protocol.

There are two ways to define an IP address. There are two types of IP addresses: IPv4 and IPv6. IP Address is defined as a 32-bit number in IPv4. An IP Address is defined as a 128-bit number in IPv6.

172.15.254.1 is an example of an IPv4 address.

IPv6 address example: 2000:0db8:85a3:0000:0000:8a2e:0370:7334

In this tutorial, we will use the socket library to get our computer’s IP address.

To obtain our computer’s IP address, we will utilize the socket library method gethostbyname(). It accepts a hostname as an argument and returns the host’s IPv4 address.

Program to get the IP Address of your Computer in Python

Approach:

  • To utilize the method gethostbyname() in the socket library, first import the socket module using the import statement.
  • To obtain the IP address of the host, we must give hostname as an argument to gethostbyname (). So, let’s acquire our computer’s hostname using the gethostname() method and send it as an argument to gethostbyname() to get the IP address.
  • Also, assign the variable the value provided by the gethostbyname() method.
  • Print the IP address of the computer.

Below is the implementation:

# To utilize the method gethostbyname() in the socket library,
# first import the socket module using the import statement.
import socket
# To obtain the IP address of the host,
# we must give hostname as an argument to gethostbyname ().
# So, let's acquire our computer's hostname using the gethostname() method
# and send it as an argument to gethostbyname() to get the IP address.
# Also, assign the variable the value provided by the gethostbyname() method.

compIpAdress = socket.gethostbyname(socket.gethostname())
# Print the IP address of the computer.
print("The IP Address of this computer is [", compIpAdress, ']')

Output:

The IP Address of this computer is [ 10.98.152.178 ]

Related Programs:

Python Program to get the IP Address of your Computer Read More »

Rotate an Image by an Angle in Python

Rotate an Image by an Angle in Python

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

In this tutorial, we’ll look at how to rotate a picture by an angle in Python.

When we say that a picture has been rotated, we indicate that the image has been rotated to a specific degree by its centre.

Rotate an Image by an Angle in Python

Below are the ways to Rotate an Image by an Angle in Python.

Method #1: Using Python Image Library(PIL)

PIL (Python Image Library) is a module that includes built-in functions for manipulating and working with images as input to the functions.

PIL has a built-in image.rotate(angle) method to rotate an image by an angle.

Syntax:

image.rotate(angle)

To load an image or give an image to the rotate() method, use the following code :

Image. open ( r” Path of the image ” )

To display the image, we’ll need to use the code below:

image.show()

Below is the Implementation:

#importing image from PIL
from PIL import Image 
 
#open the image by providing the image Path
imge = Image.open(r"D:\repeat\matrix.jpg") 
#Rotating Image by 145 degrees
rotate_imge= imge.rotate(145)
#Displaying the image
rotate_imge.show()

Before Rotation:

After Rotation:

Method #2: Using OpenCV

OpenCV:

OpenCV is a large open-source library for computer vision, machine learning, and image processing, and it currently plays a significant part in real-time operation, which is critical in today’s systems. It can process photos and movies to recognize items, faces, and even human handwriting. Python can process the OpenCV array structure for analysis when combined with other libraries such as NumPy. We employ vector space and execute mathematical operations on these features to identify visual patterns and their various features.

It has a variety of built-in capabilities for dealing with user-supplied photos.

To alter and work with images, OpenCV works brilliantly with another image processing library called imutils.

In Python, the imutils.rotate() function is used to rotate an image by an angle.

imutils.rotate(image, angle=angle)

Syntax  For Reading Image using OpenCV

cv2.imread(r”Path of the image”)

Syntax  to display the image using OpenCV

cv2.imshow(“output message”,imagevariable)

Below is the implementation:

#importing opencv and imutils 
import cv2
import imutils

#open the image by providing the image Path
imge = cv2.imread(r"D:\repeat\BTechGeeks (100).png")
 #Rotating Image by 145 degrees
rotate_imge = imutils.rotate(imge, angle=145)
#Displaying the image
cv2.imshow("Rotated Image", rotate_imge)
cv2.waitKey(0)

Before Rotation:

After Rotation:


Related Programs:

Rotate an Image by an Angle in Python Read More »

Difference between find() and index() in Python

Difference between find() and index() in Python

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

In this article, we’ll look at the differences between Python’s find() and index() functions. Both of these string approaches are fairly similar, with only a few exceptions. Before we go into the changes, let’s look at the find() and index() functions in Python.

Difference between find() and index() in Python

1)find() method in Python

find() is used to detect the place in a string where a substring is first found. Find(), in other words, returns the index of the first occurrence of a substring in a string. find() takes three parameters: the substring to be searched, the index of start, and the index of the end (the substring is searched between the start and end indexes of the string), the indexes of start and end being optional.

givenstring.find('substring',start,end)
givenstring.find('substring',start)
givenstring.find('substring')

find() returns -1 if the substring is not found in a string.

Below is the implementation:

gvnstring = 'hello this is btechgeeks python'
print(gvnstring.find('this'))
print(gvnstring.find('is', 1, 8))
print(gvnstring.find('this', 5))
res = gvnstring.find('online')
if (res != -1):
    print('The string [online] is found in given string [', gvnstring, ']')
else:
    print('The string [online] is not found in given string [', gvnstring, ']')

Output:

6
-1
6
The string [online] is not found in given string [ hello this is btechgeeks python ]

2)index() method in Python

The index() method, like find(), finds the position in a string where a substring is first found. Similarly, index() accepts three parameters: the substring to be searched, the index of start, and the index of the end (the substring is searched between the start and end indexes of the string), the indexes of start and end being optional.

givenstring.index('substring',start,end)
givenstring.index('substring',start)
givenstring.index('substring')

index() raises a ValueError if the substring is not found in a string.

Below is the implementation:

gvnstring = 'hello this is btechgeeks python'
print(gvnstring.index('this'))
print(gvnstring.index('is', 1, 20))
print(gvnstring.index('this', 5))
res = gvnstring.index('online')
if (res != -1):
    print('The string [online] is found in given string [', gvnstring, ']')
else:
    print('The string [online] is not found in given string [', gvnstring, ']')

Output:

6
8
6
Traceback (most recent call last):
File "./prog.py", line 5, in <module>
ValueError: substring not found

3)Differences Between find() and index() functions in Python

Find() gives -1 if a substring is not found in a string, whereas index() throws a ValueError exception.
As a result, find() can be used in conditional statements (if, if-else, if-elif) that run statement blocks depending on the existence of a substring in a string. However, the index() method cannot be used in conditional statements because it will generate an error.
find() can only be used with strings, but index() can be used with lists, tuples, and strings.
Related Programs:

Difference between find() and index() in Python Read More »

Program to Accept a Sentence and Print only the First Letter of Each Word in Capital Letters Separated by a Full Stop

Python Program to Accept a Sentence and Print only the First Letter of Each Word in Capital Letters Separated by a Full Stop

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Given a string(sentence) the task is to Print only the First Letter of Each Word in Capital Letters Separated by a Full Stop in Python.

Examples:

Example1:

Input:

Given string =hello this is btechgeeks 21 python

Output:

H.T.I.B.P.

Example2:

Input:

Given string =good morning this is btechgeeks online coding 24 platform for btech students

Output:

G.M.T.I.B.O.C.P.F.B.S.

Program to Accept a Sentence and Print only the First Letter of Each Word in Capital Letters Separated by a Full Stop in Python

Below are the ways to Print only the First Letter of Each Word in Capital Letters Separated by a Full Stop in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the sentence/string as static input and store it in a variable.
  • Split the sentence into a list of words using the built-in split() function.
  • Take an empty string to say resultstrng and initialize with the null value using “”.
  • Traverse in this list of words using the For loop.
  • Check if the word is alphabet or not using the If statement and isalpha() function
  • If it is true then, Convert the first letter of the word of the string to the upper using the upper function and store it in a variable.
  • Concatenate dot character to the above variable using string concatenation.
  • Add this result to resultstrng using string concatenation.
  • Print resultstrng.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as static input and store it in a variable.
gvnstrng = 'hello this is btechgeeks 21 python'
# Split the sentence into a list of words using the built-in spit() function.
gvnstrngwords = gvnstrng.split()
# Take an empty string to say resultstrng and initialize with the null value using "".
resultstrng = ""
# Traverse in this list of words using the For loop.
for strngword in gvnstrngwords:
        # Check if the word is alphabet or not using the If statement and isalpha() function
    if(strngword.isalpha()):
                # If it is true then, Convert the first letter of the word of
        # the string to the upper using the upper function and store it in a variable.
        firstchar = strngword[0].upper()
        # Concatenate dot character to the above variable using string concatenation.
        firstchar = firstchar+"."
        # Add this result to resultstrng using string concatenation.
        resultstrng = resultstrng+firstchar

# Print resultstrng.
print(resultstrng)

Output:

H.T.I.B.P.

Method #2: Using For Loop (User Input)

Approach:

  • Give the sentence/string as user input using the input() function and store it in a variable.
  • Split the sentence into a list of words using the built-in split() function.
  • Take an empty string to say resultstrng and initialize with the null value using “”.
  • Traverse in this list of words using the For loop.
  • Check if the word is alphabet or not using the If statement and isalpha() function
  • If it is true then, Convert the first letter of the word of the string to the upper using the upper function and store it in a variable.
  • Concatenate dot character to the above variable using string concatenation.
  • Add this result to resultstrng using string concatenation.
  • Print resultstrng.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as user input using the input() function
# and store it in a variable.
gvnstrng = input('Enter some random string/sentence = ')
# Split the sentence into a list of words using the built-in spit() function.
gvnstrngwords = gvnstrng.split()
# Take an empty string to say resultstrng and initialize with the null value using "".
resultstrng = ""
# Traverse in this list of words using the For loop.
for strngword in gvnstrngwords:
        # Check if the word is alphabet or not using the If statement and isalpha() function
    if(strngword.isalpha()):
                # If it is true then, Convert the first letter of the word of
        # the string to the upper using the upper function and store it in a variable.
        firstchar = strngword[0].upper()
        # Concatenate dot character to the above variable using string concatenation.
        firstchar = firstchar+"."
        # Add this result to resultstrng using string concatenation.
        resultstrng = resultstrng+firstchar

# Print resultstrng.
print(resultstrng)

Output:

Enter some random string/sentence = good morning this is btechgeeks online coding 24 platform for btech students
G.M.T.I.B.O.C.P.F.B.S.

Related Programs:

Python Program to Accept a Sentence and Print only the First Letter of Each Word in Capital Letters Separated by a Full Stop Read More »

Program to Evaluate a Postfix Expression Using Stack

Python Program to Evaluate a Postfix Expression Using Stack

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Postfix Expression:

A postfix expression (also known as Reverse Polish Notation) consists of a single letter or operator followed by two postfix strings. Every postfix string that is longer than a single variable has two operands followed by an operator.

Algebraic expressions are represented using the Postfix notation. Because parenthesis is not required in postfix notation, expressions written in postfix form are evaluated faster than expressions written in infix notation. We’ve talked about infix-to-postfix conversion. The evaluation of postfix expressions is described in this post.

Examples:

Example1:

Input:

given postfix Expression=”91-82×63+”

Output:

The value of the given postfix expression = 9

Example2:

Input:

given postfix Expression="72/96-8+"

Output:

The value of the given postfix expression = 11

Given a Postfix Expression, the task is to evaluate the given postfix Expression using a stack in Python.

Program to Evaluate a Postfix Expression Using a Stack in Python

1)Algorithm:

Using a stack, we can quickly compute a postfix expression. The objective is to go from left to right via the given postfix phrase. Push the operand into the stack if the current character in the expression is an operand; otherwise, if the current character is an operator, pop the top two elements from the stack, evaluate them using the current operator, and push the result back into the stack. After we’ve processed all of the expression characters, there will be only one element in the stack carrying the value of a postfix expression.

2)Implementation(Static Input)

Approach:

  • Give the postfix Expression as static input and store it in a variable.
  • Pass the given postfix Expression as an argument to evalpostfix function
  • Create a stack by taking an empty list which acts as a stack in this case to hold operands (or values).
  • Traverse the given postfix expression using For loop.
  • Do the following for each scanned element.
    a) Push the element into the stack if it is a number.
    b) Evaluate the operator and return the answer to the stack.
  • If the operator is ‘+’ then perform an addition operation on the top two elements by popping them out.
  • If the operator is ‘-‘ then perform a subtraction operation on the top two elements by popping them out.
  • If the operator is ‘/’ then perform a division operation on the top two elements by popping them out.
  • If the operator is ‘*’ then perform a multiplication operation on the top two elements by popping them out.
  • The only number in the stack is the final answer when the expression is traversed.
  • The Exit of the Program.

Below is the implementation:

# Function which accepts the given postfix expression as argument
# and evaluates the expression using stack and return the value


def evaluatePostfix(givenExp):

    # Create a stack by taking an empty list which acts
    # as a stack in this case to hold operands (or values).
    givenstack = []

    # Traverse the given postfix expression using For loop.
    for charact in givenExp:

        # Push the element into the given stack if it is a number.
        if charact.isdigit():
            givenstack.append(int(charact))

        # if the character is operator
        else:
            # remove the top two elements from the stack
            topfirst = givenstack.pop()
            topsecond = givenstack.pop()

            # Evaluate the operator and return the answer to the stack using append() funtion.
            # If the operator is '+' then perform an addition operation on
            # the top two elements by popping them out.
            if charact == '+':
                givenstack.append(topsecond + topfirst)
            # If the operator is '-' then perform a subtraction operation
            # on the top two elements by popping them out.
            elif charact == '-':
                givenstack.append(topsecond - topfirst)
            # If the operator is '/' then perform a division operation on
            # the top two elements by popping them out.
            elif charact == '×':
                givenstack.append(topsecond * topfirst)
            # If the operator is '*' then perform a multiplication operation
            # on the top two elements by popping them out.
            elif charact == '/':
                givenstack.append(topsecond // topfirst)

    # The only number in the stack is the final answer when the expression is traversed.
    # return the answer to the main function
    return givenstack.pop()


# Driver code
# Give the postfix Expression as static input and store it in a variable.
givenExp = "91-82×63+"
# Pass the given postfix Expression as an argument to evalpostfix function
print('The value of the given postfix expression =', evaluatePostfix(givenExp))

Output:

The value of the given postfix expression = 9

3)Implementation(User Input)

Approach:

  • Give the postfix Expression as user input using the input() function and store it in a variable.
  • Pass the given postfix Expression as an argument to evalpostfix function
  • Create a stack by taking an empty list which acts as a stack in this case to hold operands (or values).
  • Traverse the given postfix expression using For loop.
  • Do the following for each scanned element.
    a) Push the element into the stack if it is a number.
    b) Evaluate the operator and return the answer to the stack.
  • If the operator is ‘+’ then perform an addition operation on the top two elements by popping them out.
  • If the operator is ‘-‘ then perform a subtraction operation on the top two elements by popping them out.
  • If the operator is ‘/’ then perform a division operation on the top two elements by popping them out.
  • If the operator is ‘*’ then perform a multiplication operation on the top two elements by popping them out.
  • The only number in the stack is the final answer when the expression is traversed.
  • The Exit of the Program.

Below is the implementation:

# Function which accepts the given postfix expression as argument
# and evaluates the expression using stack and return the value


def evaluatePostfix(givenExp):

    # Create a stack by taking an empty list which acts
    # as a stack in this case to hold operands (or values).
    givenstack = []

    # Traverse the given postfix expression using For loop.
    for charact in givenExp:

        # Push the element into the given stack if it is a number.
        if charact.isdigit():
            givenstack.append(int(charact))

        # if the character is operator
        else:
            # remove the top two elements from the stack
            topfirst = givenstack.pop()
            topsecond = givenstack.pop()

            # Evaluate the operator and return the answer to the stack using append() funtion.
            # If the operator is '+' then perform an addition operation on
            # the top two elements by popping them out.
            if charact == '+':
                givenstack.append(topsecond + topfirst)
            # If the operator is '-' then perform a subtraction operation
            # on the top two elements by popping them out.
            elif charact == '-':
                givenstack.append(topsecond - topfirst)
            # If the operator is '/' then perform a division operation on
            # the top two elements by popping them out.
            elif charact == '×':
                givenstack.append(topsecond * topfirst)
            # If the operator is '*' then perform a multiplication operation
            # on the top two elements by popping them out.
            elif charact == '/':
                givenstack.append(topsecond // topfirst)

    # The only number in the stack is the final answer when the expression is traversed.
    # return the answer to the main function
    return givenstack.pop()


# Driver code
# Give the postfix Expression as user input using input() function and store it in a variable.
givenExp = input('Enter some random postfix Expression = ')
# Pass the given postfix Expression as an argument to evalpostfix function
print('The value of the given postfix expression =', evaluatePostfix(givenExp))

Output:

Enter some random postfix Expression = 72/96-8+
The value of the given postfix expression = 11

Related Programs:

Python Program to Evaluate a Postfix Expression Using Stack Read More »

Program to Perform XOR on Two Lists

Python Program to Perform XOR on Two Lists

Given two lists of the same length, the task is to perform the Xor Operation on both the list elements which are having the same index in Python.

Examples:

Example1:

Input:

Given list 1= [4, 19, 11, 5, 3, 9, 7]
Given list 2= [10, 3, 7, 2, 9, 8, 6, 5]

Output:

The given First list elements are = [4, 19, 11, 5, 3, 9, 7]
The given Second list elements are = [10, 3, 7, 2, 9, 8, 6, 5]
The result after applying xor operation on both lists is [14, 16, 12, 7, 10, 1, 1]

Example2:

Input:

Given list 1 = [5, 7, 9, 6]
Given list 2 = [3, 8, 9, 4]

Output:

The given First list elements are = [5, 7, 9, 6]
The given Second list elements are = [3, 8, 9, 4]
The result after applying xor operation on both list is [6, 15, 0, 2]

Program to Perform XOR on Two Lists in Python

Below are the ways to perform Xor on Two lists in Python.

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Method #1: Using For Loop (Static Input)

Approach:

  • Give the first list as static input and store it in a variable.
  • Give the second list as static input and store it in another variable.
  • Calculate the length of the first list using the len() function(as both lists have same length) and store it in a variable.
  • Loop till the above length using the For loop.
  • Inside the for loop initialize the list 1 element as xor operation between list1 and list2 using xor operator i.e lst1[p]=lst1[p]^lst2[p] where p is the iterator value of the For loop.
  • Print the list1 which is the result.
  • The Exit of Program.

Below is the implementation:

# Give the first list as static input and store it in a variable.
lstt1 = [4, 19, 11, 5, 3, 9, 7]
# Give the second list as static input and store it in another variable.
lstt2 = [10, 3, 7, 2, 9, 8, 6, 5]
print('The given First list elements are =', lstt1)
print('The given Second list elements are =', lstt2)
# Calculate the length of the first list using the len()
# function(as both lists have same length) and store it in a variable.
lenlst = len(lstt1)
# Loop till the above length using the For loop.
for p in range(lenlst):
    # Inside the for loop initialize the list 1 element as xor operation
    # between list1 and list2 using xor operator i.e lst1[p]=lst1[p]^lst2[p]
    # where p is the iterator value of the For loop.
    lstt1[p] = lstt1[p] ^ lstt2[p]
# Print the list1 which is the result.
print('The result after applying xor operation on both lists is', lstt1)

Output:

The given First list elements are = [4, 19, 11, 5, 3, 9, 7]
The given Second list elements are = [10, 3, 7, 2, 9, 8, 6, 5]
The result after applying xor operation on both lists is [14, 16, 12, 7, 10, 1, 1]

Method #2: Using For Loop (User Input)

Approach:

  • Give the first list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the second list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the length of the first list using the len() function(as both lists have same length) and store it in a variable.
  • Loop till the above length using the For loop.
  • Inside the for loop initialize the list 1 element as xor operation between list1 and list2 using xor operator i.e lst1[p]=lst1[p]^lst2[p] where p is the iterator value of the For loop.
  • Print the list1 which is the result.
  • The Exit of Program.

Below is the implementation:

# Give the first list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
lstt1 = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the second list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
lstt2 = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
print('The given First list elements are =', lstt1)
print('The given Second list elements are =', lstt2)
# Calculate the length of the first list using the len()
# function(as both lists have same length) and store it in a variable.
lenlst = len(lstt1)
# Loop till the above length using the For loop.
for p in range(lenlst):
    # Inside the for loop initialize the list 1 element as xor operation
    # between list1 and list2 using xor operator i.e lst1[p]=lst1[p]^lst2[p]
    # where p is the iterator value of the For loop.
    lstt1[p] = lstt1[p] ^ lstt2[p]
# Print the list1 which is the result.
print('The result after applying xor operation on both lists is', lstt1)

Output:

Enter some random List Elements separated by spaces = 5 7 9 6
Enter some random List Elements separated by spaces = 3 8 9 4
The given First list elements are = [5, 7, 9, 6]
The given Second list elements are = [3, 8, 9, 4]
The result after applying xor operation on both list is [6, 15, 0, 2]

Related Programs:

Python Program to Perform XOR on Two Lists Read More »