Author name: Vikram Chiluka

Program to Compute the Area and Perimeter of Octagon

Python Program to Compute the Area and Perimeter of Octagon

In the previous article, we have discussed Python Program to Compute the Area and Perimeter of Heptagon
Math Module :

Python’s math module is a built-in module. By importing this module, we can perform mathematical computations.

Numerous mathematical operations like ceil( ),floor( ),factorial( ),mod( ),value of pi ,…..etc .can be computed with the help of math module.

Octagon:

An octagon is a polygon with eight sides. It has eight different angles.

Octagon = octa + gon, where octa is the number eight and gon is the number of sides.

In an octagon, there are 20 diagonals.

Formula to calculate the area of an Octagon:

A = 2(1+⎷2)a²
In which  a is the Octagon’s side length
Formula to calculate the perimeter of a Octagon:
perimeter = 8a
Given the Octagon’s side length and the task is to calculate the area and perimeter of the given Octagon.
Examples:

Example1:

Input:

Given The Octagon's side length = 6

Output:

The Octagon's Area with given side length { 6 } = 173.82337649086284
The Octagon's Perimeter with the given side length { 6 } = 48

Example2:

Input:

Given The Octagon's side length = 12.5

Output:

The Octagon's Area with given side length { 12.5 } = 754.4417382415921
The Octagon's Perimeter with the given side length { 12.5 } = 100.0

Program to Compute the Area and Perimeter of Octagon

Below are the ways to Calculate the area and perimeter of a heptagon with the given Octagon’s side length:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Import the math module using the import keyword.
  • Give the Octagon’s side length as static input and store it in a variable.
  • Calculate the area of the given Octagon using the above given mathematical formula and sqrt(), math.pow() functions.
  • Store it in another variable.
  • Calculate the perimeter of the given Octagon using the above given mathematical formula.
  • Store it in another variable.
  • Print the Octagon’s area with the given side length.
  • Print the Octagon’s perimeter with the given side length.
  • The Exit of the program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the Octagon's side length as static input and store it in a variable.
side_len = 6
# Calculate the area of the given Octagon using the above given mathematical formula
# and sqrt(), math.pow() functions.
# Store it in another variable.
octgn_area = (2*(1+math.sqrt(2))*math.pow(side_len, 2))
# Calculate the perimeter of the given Octagon using the above given mathematical formula.
# Store it in another variable.
octgn_perimetr = (8*side_len)
# Print the Octagon's area with the given side length.
print(
    "The Octagon's Area with given side length {", side_len, "} =", octgn_area)
# Print the Octagon's perimeter with the given side length.
print(
    "The Octagon's Perimeter with the given side length {", side_len, "} =", octgn_perimetr)

Output:

The Octagon's Area with given side length { 6 } = 173.82337649086284
The Octagon's Perimeter with the given side length { 6 } = 48

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Import the math module using the import keyword.
  • Give the Octagon’s side length as user input using float(input()) function and store it in a variable.
  • Calculate the area of the given Octagon using the above given mathematical formula and sqrt(), math.pow() functions.
  • Store it in another variable.
  • Calculate the perimeter of the given Octagon using the above given mathematical formula.
  • Store it in another variable.
  • Print the Octagon’s area with the given side length.
  • Print the Octagon’s perimeter with the given side length.
  • The Exit of the program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the Octagon's side length as user input using float(input()) function and
# store it in a variable.
side_len = float(input("Enter some random number = "))
# Calculate the area of the given Octagon using the above given mathematical formula
# and sqrt(), math.pow() functions.
# Store it in another variable.
octgn_area = (2*(1+math.sqrt(2))*math.pow(side_len, 2))
# Calculate the perimeter of the given Octagon using the above given mathematical formula.
# Store it in another variable.
octgn_perimetr = (8*side_len)
# Print the Octagon's area with the given side length.
print(
    "The Octagon's Area with given side length {", side_len, "} =", octgn_area)
# Print the Octagon's perimeter with the given side length.
print(
    "The Octagon's Perimeter with the given side length {", side_len, "} =", octgn_perimetr)

Output:

Enter some random number = 12.5
The Octagon's Area with given side length { 12.5 } = 754.4417382415921
The Octagon's Perimeter with the given side length { 12.5 } = 100.0

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Compute the Area and Perimeter of Octagon Read More »

Python Programs for Beginners

Python Programs for Beginners | Basic to Advanced Python Practice Programs for Beginners

Basic Python Programs for Beginners Pdf: This tutorial of python programs for beginners aid you to learn all basics to advanced concepts of python programming. An effective way to gain knowledge and learn the python programming language is by practicing all basic to advanced python concepts example programs. It will extremely helpful for all beginners of python learning.

To make you feel relaxed in searching all simple python practice programs for beginners, we have curated a list of all example programs on concepts of python. Make use of this ultimate tutorial on Python programming for beginners to learn completely & practice efficiently to become proficient in the python programming language.

Python Programs for Practice | List of Popular Python Programs for Freshers and Experienced

Python Basic Programs

Python Conversion Programs

Python Mathematical Programs

Python Decision Making and Loop Programs

Python Class and Object Programs

Python String Programs

Python Algorithms Programs

Python Files Programs

Python Dictionary Programs

Python Pattern Printing Programs

Python Searching Programs

Python List Programs

Python Nested Lists / 2-d List Programs

Python Date and Time Programs

Python Simple Programs on Special Numbers

Python Programming Examples on Fibonacci and Complex Numbers

Python Recursion Programs

Python Hashing/Frequency Programs

Python Number Theory Programs

Python Sorting Programs

Python Range Programs

Python Bit Manipulation Programs

Python Sentence Programs

Python Tuple Programs

Python Number Series Programs

Python Miscellaneous Programs

FAQs on Free Beginners Python Programs Tutorial

1. Is Python programming easy for learning to beginners?

Of course, yes. Beginners and experienced programmers in another programming language can easily learn the python programming language. So, save your valuable time & please jump into the world of python.

2. What are the best tips to code python programs for beginners?

Just have a look at the following tips and implement them while beginners start coding in python for the first time:

  • Choose basic to advance python programs for beginners from the above list
  • Code Everyday & Practice well
  • Go Interactive
  • Write it Out
  • Always learn with other passionate python learners
  • Teach others
  • Raise & Clear Good queries while coding
  • Go Forth and Learn!

3. Which Python Version is best for beginners?

In beneficial to compatibility with third-party modules, the safest version of python to pick is the current one ie., the Python 3.8.1 version.

4. How do I start Python programming for beginners?

Simply select the best Python Programming Online Tutorial from the reliable and trustworthy website and go with the site to search for python programs for beginners. After going through the concepts of the python programming language @btechgeeks.com start practicing basic python programs for beginners from the list available above.

Python Programs for Beginners | Basic to Advanced Python Practice Programs for Beginners Read More »

Python: How to Create an Empty List and Append Items to it?

An ordered list of values is a collection. There may be different types of values. A list is a container that is mutable. This means that the existing ones can be added, deleted, or modified.

The list of Pythons represents a finite sequence mathematical concept. List values are called list items or list elements. A list may multiple times contain the same value. Each event is considered to be a separate element.

In this article, we will look at how to create an empty list and add elements to the list in Python.

How to Create An Empty List and How to Append a list of Items in Python?

There are several ways to create and append values to list some of them are:

Creating a list:

Adding elements to list:

Creating a list

Method #1: Using [] symbol create an empty list in python

An empty list can be generated in Python by simply writing square brackets, i.e. []. If there are no arguments in the square brackets [, it returns an empty list.

Using [] symbol

Implementation:

# creating new list
newlist = []
# printing it
print("Newlist = ", newlist)

Output:

Newlist =  []

Method #2: Using list() Constructor create an empty list in python

The list class in Python has a constructor

list( [iterable] ).

It takes an optional statement, which is an iterable sequence, and constructs a list from these elements. It returns an empty list if Sequence is not given. Let’s use this to make a blank list.

Using list() Constructor

Implementation:

# creating new list
newlist = list()
# printing it
print("Newlist = ", newlist)

Output:

Newlist =  []

Adding items/elements to the list

Method #1: Using append() function add items to an empty list in python

The built-in append() function can be used to add elements to the List. The append() method can only add one element to the list at a time; loops are used to add several elements to the list with the append() method. Since tuples are immutable, they can also be added to the list using the append method. Lists, unlike Sets, can be appended to an existing list using the append() form.

Using append() function

Below is the implementation:

# creating new empty list
newlist = list()
# adding items 1 2 3 to it
newlist.append(1)
newlist.append(2)
newlist.append(3)
# printing it
print("Newlist = ", newlist)

Output:

Newlist =  [1, 2, 3]

Method #2:Using insert() function add elements to an empty list in python

insert():

It inserts the item in the list at the given index.

list.insert(index,element)

The append() method only adds elements to the end of the List; the insert() method is used to add elements to the desired location. Unlike append(), which only needs one statement, insert() requires two (index,element).

creating new empty list Using insert() function

Below is the implementation:

# Taking a list with values
newlist = ['this', 'is', 'BTechGeeks']
# inserting element hello to 2 nd index using insert()
newlist.insert(2, 'hello')
# printing the list
print("list = ", newlist)

Output:

list =  ['this', 'is', 'hello', 'BTechGeeks']

Method #3:Using extend() function add items to an empty list in python

There is one more method to add elements other than the append() and insert() methods, extend(), used at the end of the list to add multiple elements simultaneously.

Note: the methods append() and extend() can only add elements at the end.

Below is the implementation:

# Taking a list with values
newlist = ['this', 'is', 'BTechGeeks']
# extend this newlist with multiple items
newlist.extend(['hello', 'python', 234])
# printing the list
print("list = ", newlist)

Output:

list =  ['this', 'is', 'BTechGeeks', 'hello', 'python', 234]

Related Programs:

Python: How to Create an Empty List and Append Items to it? Read More »

Program to Check Whether the given Two Numbers are Amicable Numbers or Not

Python Program to Check Whether the given Two Numbers are Amicable Numbers or Not

Wondering how to find if two numbers given are Amicable or Not? Then, you have come the right way as we will explain what are Amicable Numbers and Python Program to Check if Two Numbers are Amicable Numbers or not. Refer to the Various Methods for Checking if given Numbers are Amicable or Not and use the method you are comfortable with.

Amicable Numbers in Python

First and foremost, what exactly is this Amicable? We say two numbers are Amicable if the sum of their proper divisors is equal to the opposite numbers, that is, the sum of x’s divisors is equal to y and the sum of y’s divisors is equal to x. We can grasp it better by using an example.

Take 234 and 339 as two numbers; now find the divisors of 123 and 456; their sums will be sum1 and sum2, respectively. Then sum2 must equal 123 and sum1 must equal 456.

We should determine all the suitable divisors of x ,y and add them separately before matching them to the opposite numbers; if they match, we claim the two numbers are amicable; otherwise, we say they are not.

sumX=y,

sumY=x

Where sumX is the sum of all proper divisors of the number x.

Where sumY is the sum of all proper divisors of the number y.

Examples:

Example 1:

Input:

given number1 =220 ;       given number2=284

Output:

The given numbers 220 and 284 are amicable numbers

Example 2:

Input:

given number1= 339    ; given number2=134

Output:

The given numbers 339 and 134 are not amicable numbers

Python Program to Check Whether the given Two Numbers are Amicable Numbers or Not

There are several ways to check whether the given number is given Two Number are Amicable Numbers or Not, some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

All of the methods follow a similar technique but differ in terms of time complexity. Methods for obtaining divisors are classified below based on their time complexity:

Method #1: Iterating from 2 to N-1

Approach:

  • Take both integers and store them in different variables.
  • Calculate the sum of the proper divisors of both numbers ( loop from 2 to given_number-1, keep track of the sum of the number’s proper divisors)
  • Repeat the above step for number2
  • Examine whether the total of the proper divisors equals the opposite numbers.
  • They are amicable numbers if they are equal.
  • The final result should be printed.

Below is the implementation:

Python Program to Check Whether the Given Numbers are Amicable Numbers or Not

# python program to cheeck whether the given number is Amicable numbers or not

# function which returns true if the given number is
# Amicable numbers else it will return False


def checkAmicableNumb(given_numb1, given_numb2):
    # Taking a variable totalSum1 and initializing it with 1
    totalSum1 = 1
    # Iterating from 2 to n-1
    for i in range(2, given_numb1):
        # if the iterator value is divides the number then add the given
        # number to totalSum1
        if given_numb1 % i == 0:
            totalSum1 += i
    # repeating the same step for number 2
    # Taking a variable totalSum2 and initializing it with 1
    totalSum2 = 1
    # Iterating from 2 to n-1
    for i in range(2, given_numb2):
        # if the iterator value is divides the number then add the given
        # number to totalSum2
        if given_numb2 % i == 0:
            totalSum2 += i

    # if the totalSum1 is equal to the given number2 and
    # totalSum2 is equal to the given number1 then both the numbers are amicable numbers
    # else they are not amicable numbers

    if(totalSum1 == given_numb2 and totalSum2 == given_numb1):
        # if it is true then they are amicable numbers so return true
        return True
    # if nothing is returned then they are not a amicable numbers so return False
    return False


# Given two numbers
# given number1(numb1)
given_numb1 = 220
# given number2(numb2)
given_numb2 = 284
# passing the given two numbers to checkAmicableNumb to check whether it is
# Amicable numbers or not
if(checkAmicableNumb(given_numb1, given_numb2)):
    print("The given numbers", given_numb1, "and",
          given_numb2, "are amicable numbers")
else:
    print("The given numbers", given_numb1, "and",
          given_numb2, "are not amicable numbers")

Output:

The given numbers 220 and 284 are amicable numbers

It requires O(n) Time Complexity.

Method #2:Iterating from 2 to N/2

Approach:

  • Take both integers and store them in different variables.
  • Calculate the sum of the proper divisors of both numbers ( loop from 2 to given_number//2, keep track of the sum of the number’s proper divisors)
  • Repeat the above step for number2
  • Examine whether the total of the proper divisors equals the opposite numbers.
  • They are amicable numbers if they are equal.
  • The final result should be printed.

Below is the implementation:

# python program to cheeck whether the given number is Amicable numbers or not

# function which returns true if the given number is
# Amicable numbers else it will return False


def checkAmicableNumb(given_numb1, given_numb2):
    # Taking a variable totalSum1 and initializing it with 1
    totalSum1 = 1
    # Iterating from 2 to n-1
    for i in range(2, given_numb1//2 + 1):
        # if the iterator value is divides the number then add the given
        # number to totalSum1
        if given_numb1 % i == 0:
            totalSum1 += i
    # repeating the same step for number 2
    # Taking a variable totalSum2 and initializing it with 1
    totalSum2 = 1
    # Iterating from 2 to n-1
    for i in range(2, given_numb2//2 + 1):
        # if the iterator value is divides the number then add the given
        # number to totalSum2
        if given_numb2 % i == 0:
            totalSum2 += i

    # if the totalSum1 is equal to the given number2 and
    # totalSum2 is equal to the given number1 then both the numbers are amicable numbers
    # else they are not amicable numbers

    if(totalSum1 == given_numb2 and totalSum2 == given_numb1):
        # if it is true then they are amicable numbers so return true
        return True
    # if nothing is returned then they are not a amicable numbers so return False
    return False


# Given two numbers
# given number1(numb1)
given_numb1 = 220
# given number2(numb2)
given_numb2 = 284
# passing the given two numbers to checkAmicableNumb to check whether it is
# Amicable numbers or not
if(checkAmicableNumb(given_numb1, given_numb2)):
    print("The given numbers", given_numb1, "and",
          given_numb2, "are amicable numbers")
else:
    print("The given numbers", given_numb1, "and",
          given_numb2, "are not amicable numbers")

Output:

The given numbers 220 and 284 are amicable numbers

It requires O(n) Time Complexity.

It reduces half the number of iterations.

Method #3: Efficient Approach (Iterating till Square root of N)

Approach:

  • Take both integers and store them in different variables.
  • Calculate the sum of the proper divisors of both numbers (go through the numbers till you get to the square root of n. If a number i divides n, then sum both i and n/i)
  • Repeat the above step for number2
  • Examine whether the total of the proper divisors equals the opposite numbers.
  • They are amicable numbers if they are equal.
  • The final result should be printed.

Below is the implementation:

# python program to cheeck whether the given number is Amicable numbers or not

# function which returns true if the given number is
# Amicable numbers else it will return False


def checkAmicableNumb(given_numb1, given_numb2):
    # Taking a variable totalSum1 and initializing it with 1
    totalSum1 = 1
    k = 2
    while k * k <= given_numb1:
        # if the iterator value is divides the number then add the given number to totalSum
        if given_numb1 % k == 0:
            totalSum1 = totalSum1 + k + given_numb1/k
        k += 1
    # repeating the same step for number 2
    # Taking a variable totalSum2 and initializing it with 1
    totalSum2 = 1
    k = 2
    while k * k <= given_numb2:
        # if the iterator value is divides the number then add the given number to totalSum
        if given_numb2 % k == 0:
            totalSum2 = totalSum2 + k + given_numb2/k
        k += 1

    # if the totalSum1 is equal to the given number2 and
    # totalSum2 is equal to the given number1 then both the numbers are amicable numbers
    # else they are not amicable numbers

    if(totalSum1 == given_numb2 and totalSum2 == given_numb1):
        # if it is true then they are amicable numbers so return true
        return True
    # if nothing is returned then they are not a amicable numbers so return False
    return False


# Given two numbers
# given number1(numb1)
given_numb1 = 220
# given number2(numb2)
given_numb2 = 284
# passing the given two numbers to checkAmicableNumb to check whether it is
# Amicable numbers or not
if(checkAmicableNumb(given_numb1, given_numb2)):
    print("The given numbers", given_numb1, "and",
          given_numb2, "are amicable numbers")
else:
    print("The given numbers", given_numb1, "and",
          given_numb2, "are not amicable numbers")

Output:

The given numbers 220 and 284 are amicable numbers

Here the given numbers 220 and 284 are amicable numbers.

This is the efficient approach to do the same problem quickly compared to the first two methods.

It requires O(Sqrt(n)) Time Complexity.

Related Programs:

Python Program to Check Whether the given Two Numbers are Amicable Numbers or Not Read More »

Python Check if Two Lists are Equal

Python: Check if Two Lists are Equal | How do you Check if a List is the Same as Another List Python?

In Order to check if two lists or identical or not we need to check if two unordered lists have similar elements in the exact similar position.  You might need this in your day-to-day programming. Go through the tutorial over here and determine if two lists are equal or not in Python easily.

We have mentioned the various techniques for finding if a list is the same as the Another or Not along with sample programs. Use them as a guide for resolving your doubts if any on Comparing Two Lists and finding whether they are identical or not. You can also find difference between two lists python by going through our other tutorials.

List – Definition

Multiple items may be stored in a single variable using lists. Square brackets[] are used to create a list. Lists are one of four built-in Python storage types for storing sets of data; the other three are Tuple, Set, and Dictionary, all of which have different qualities and applications.

Examples for Checking if Two Lists are Equal or Not

Comparing lists irrespective of the order of lists:

Input:

firstlist = ['hello', 'this', 'is', 'BTechGeeks'] 

secondlist = ['this', 'is', 'BTechGeeks','hello']

Output:

Both lists are equal

Input:

firstlist = ['hello', 'this', 'is', 'BTechGeeks','is'] 

secondlist = ['this', 'is', 'BTechGeeks','hello','the']

Output:

Both lists are not equal

Comparing list based on the order of lists:

Input:

firstlist = ['this' ,'is','BTechGeeks']
secondlist = ['this' ,'is','BTechGeeks']

Output:

Both lists are equal

Input:

firstlist = ['hello', 'this' ,'is','BTechGeeks']
secondlist = ['this' ,'is','BTechGeeks']

Output:

Both lists are not equal

How to Compare if Two Lists are Identical or Not?

There are several ways to check if two lists are equal or not. We have outlined some of them so that you can choose the method that you are comfortable with and determine if the two lists are equal or not. They are explained in the following way

  • Using sorting()
  • Using Counter() function
  • Using np.array_equal()
  • Using ‘=’ Operator
  • Using reduce() +map()

Check lists irrespective of order of elements

Method #1: Using sorting()

We start by sorting the list so that if both lists are similar, the elements are in the same place. However, this ignores the order of the elements in the list. So, by comparing sorting versions of lists, we can determine whether or not they are equal.

Below is the implementation:

# function to check both lists if they are equal
def checkList(firstlist, secondlist):
    # sorting the lists
    firstlist.sort()
    secondlist.sort()
    # if both the lists are equal the print yes
    if(firstlist == secondlist):
        print("Both lists are equal")
    else:
        print("Both lists are not equal")


# Driver code
# given two lists
firstlist = ['hello', 'this', 'is', 'BTechGeeks']
secondlist = ['this', 'is', 'BTechGeeks','hello']
# passing both the lists to checklist function
checkList(firstlist, secondlist)

Python Program to check if two lists are equal or not using Sorting()

Output:

Both lists are not equal

Method #2: Using Counter() function

We can normally get the frequency of each variable in a list using Counter(), and we can search for it in both lists to see whether they are similar or not. However, this approach disregards the order of the elements in the list and only considers the frequency of the elements.

Below is the implementation:

# importing counter function from collections
from collections import Counter

# function to check both lists if they are equal
def checkList(firstlist, secondlist):
    # Getting frequencies of both lists
    firstfreq = Counter(firstlist)
    secondfreq = Counter(secondlist)
    # if both the lists are equal the print yes
    if(firstfreq == secondfreq):
        print("Both lists are equal")
    else:
        print("Both lists are not equal")


# Driver code
# given two lists
firstlist = ['hello', 'this', 'is', 'BTechGeeks'] 
secondlist = ['this', 'is', 'BTechGeeks','hello']
# passing both the lists to checklist function
checkList(firstlist, secondlist)

Comparison of two lists using counter() function in Python

Output:

Both lists are not equal

Method #3: Using np.array_equal()

From our lists, we can generate two sorted numpy arrays, which we can compare using numpy.array equal() to see if they contain the same elements.

Below is the implementation:

# importing numpy
import numpy
# function to check both lists if they are equal
def checkList(firstlist, secondlist):
    # Convert both lists to sorted numpy arrays and compare them to see if they're equal.
    if(numpy.array_equal(numpy.array(firstlist).sort(), numpy.array(secondlist).sort())):
        print("Both lists are equal")
    else:
        print("Both lists are not equal")


# Driver code
# given two lists
firstlist = ['hello', 'this', 'is', 'BTechGeeks'] 
secondlist = ['this', 'is', 'BTechGeeks','hello']
# passing both the lists to checklist function
checkList(firstlist, secondlist)

Output:

Both lists are not equal

Checking lists based on of order of elements

Method #4: Using ‘=’ Operator

The == operator can be used to compare two lists directly. If both lists are exactly identical, it will return True; otherwise, it will return False.

Below is the implementation:

# function to check if both the lists are same
def checkList(firstlist, secondlist):
    # if both the lists are equal the print yes
    if(firstlist == secondlist):
        print("Both lists are equal")
    else:
        print("Both lists are not equal")


# Driver code
# given two lists
firstlist = ['hello', 'this', 'is', 'BTechGeeks']
secondlist = ['hello', 'this', 'is', 'BTechGeeks']
# passing both the lists to checklist function
checkList(firstlist, secondlist)

Comparison of two lists using = Operator in Python

Output:

Both lists are not equal

Method #5: Using reduce() +map()

We can accomplish this task of checking for the equality of two lists by carefully coupling the power of map() to hash values and the utility of reduce(). This also takes into account the list’s order.

Below is the implementation:

# importing reduce from functools
from functools import reduce
# function to check if both the lists are same
def checkList(firstlist, secondlist):
    # if both the lists are equal the print yes
    if(reduce(lambda a, b: a and b, map(lambda x, y: x == y, firstlist, secondlist))):
        print("Both lists are equal")
    else:
        print("Both lists are not equal")


# Driver code
# given two lists
firstlist = ['hello', 'this', 'is', 'BTechGeeks']
secondlist = ['hello', 'this', 'is', 'BTechGeeks']
# passing both the lists to checklist function
checkList(firstlist, secondlist)

Output:

Both lists are not equal

Python: Check if Two Lists are Equal | How do you Check if a List is the Same as Another List Python? Read More »

Program to Replace a Word with Asterisks in a Sentence

Python Program to Replace a Word with Asterisks in a Sentence

In the previous article, we have discussed Python Program to Find Sum of Odd Factors of a Number
Given a sentence and the task is to replace a word with asterisks in a given Sentence.

Examples:

Example1:

Input:

Given string = "hello this is btechgeeks btechgeeks"
Given word to be replaced = "btechgeeks"

Output:

The given string [ hello this is btechgeeks btechgeeks ] after replacing with a given word with an asterisk :
hello this is ********** **********

Example2:

Input:

Given string = "good morning this is btechgeeks good morning all"
Given word to be replaced = "good"

Output:

The given string [ good morning this is btechgeeks good morning all ] after replacing with a given word with an asterisk :
**** morning this is btechgeeks **** morning all

Program to Replace a Word with Asterisks in a Sentence in Python

Below are the ways to replace a word with asterisks in a given Sentence:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Give the replaceable word as static input and store it in another variable.
  • Split the given string into a list of words using the split() function and store it in another variable say “wrd_lst”.
  • Multiply the asterisk symbol with the length of the given input word using the len() function and store it in another variable say “replaced_word”.
  • Loop in the above-obtained word list using the for loop.
  • Check if the word at the iterator index is equal is given input word using the if conditional statement.
  • If the statement is true, replace the word at the iterator index with the replaced_word.
  • Convert the above-got word list to string using the join() function.
  • Print the above-obtained string to replace a word with an asterisk in a given input sentence.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "hello this is btechgeeks btechgeeks"
# Give the replaceable word as static input and store it in another variable.
gvn_wrd = "btechgeeks"
# Split the given string into a list of words using the split() function and
# store it in another variable say "wrd_lst".
wrd_lst = gvn_str.split()
# Multiply the asterisk symbol with the length of the given input word using
# the len() function and store it in another variable.
replacd_word = '*' * len(gvn_wrd)
# Loop in the above-obtained word list using the for loop.
for itr in range(len(wrd_lst)):
  # Check if the iterator value is equal to the given input word using the if
  # conditional statement.
 # check if thw word at the iterator index is equal is given
    if wrd_lst[itr] == gvn_wrd:
      # if it is truw thwn replce the word t the iterator index with the replaced word
        wrd_lst[itr] = replacd_word
# Convert the above-got word list to string using the join() function.
finl_str = ' '.join(wrd_lst)
# Print the above-obtained string to replace a word with an asterisk in a
# given input sentence.
print("The given string [", gvn_str,
      "] after replacing with a given word with an asterisk :")
print(finl_str)

Output:

The given string [ hello this is btechgeeks btechgeeks ] after replacing with a given word with an asterisk :
hello this is ********** **********

Method #2: Using For loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Give the replaceable word as user input using the input() function and store it in another variable.
  • Split the given string into a list of words using the split() function and store it in another variable say “wrd_lst”.
  • Multiply the asterisk symbol with the length of the given input word using the len() function and store it in another variable say “replaced_word”.
  • Loop in the above-obtained word list using the for loop.
  • Check if the word at the iterator index is equal is given input word using the if conditional statement.
  • If the statement is true, replace the word at the iterator index with the replaced_word.
  • Convert the above-got word list to string using the join() function.
  • Print the above-obtained string to replace a word with an asterisk in a given input sentence.
  • 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 sentence = ")
# Give the replaceable word as user input using the input() function and store it in another variable.
gvn_wrd = input("Enter some random word = ")
# Split the given string into a list of words using the split() function and
# store it in another variable say "wrd_lst".
wrd_lst = gvn_str.split()
# Multiply the asterisk symbol with the length of the given input word using
# the len() function and store it in another variable.
replacd_word = '*' * len(gvn_wrd)
# Loop in the above-obtained word list using the for loop.
for itr in range(len(wrd_lst)):
  # Check if the iterator value is equal to the given input word using the if
  # conditional statement.
 # check if thw word at the iterator index is equal is given
    if wrd_lst[itr] == gvn_wrd:
      # if it is truw thwn replce the word t the iterator index with the replaced word
        wrd_lst[itr] = replacd_word
# Convert the above-got word list to string using the join() function.
finl_str = ' '.join(wrd_lst)
# Print the above-obtained string to replace a word with an asterisk in a
# given input sentence.
print("The given string [", gvn_str,
      "] after replacing with a given word with an asterisk :")
print(finl_str)

Output:

Enter some random sentence = good morning this is btechgeeks good morning all
Enter some random word = good
The given string [ good morning this is btechgeeks good morning all ] after replacing with a given word with an asterisk :
**** morning this is btechgeeks **** morning all

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Replace a Word with Asterisks in a Sentence Read More »

Program to Sort Palindrome Words in a Sentence

Python Program to Sort Palindrome Words in a Sentence

In the previous article, we have discussed Python Program to Find the Sum of Digits of a Number at Even and Odd places
Given a string and the task is to sort all the palindrome words in a given sentence.

Palindrome:

If the reverse of the given string is the same as the given original string, it is said to be a palindrome.

Example :

Given string = “sos asked to bring the madam pip “.

Output :

Explanation: In this “madam”, “pip”, “sos” are the palindromic words. By sorting them we get {“madam”, ‘pip’ , “sos”}

Examples:

Example1:

Input:

Given string/sentence ='sos how are you madam pip instal'

Output:

The given string before sorting all the palindromic words is =  sos how are you madam pip instal
The final string after sorting all the palindromic words is =  madam how are you pip sos instal

Example2:

Input:

Given string/sentence = 'the good is madam aba dad mom din cac'

Output:

The given string before sorting all the palindromic words is = the good is madam aba dad mom din cac
The final string after sorting all the palindromic words is = the good is aba cac dad madam din mom

Program to Sort Palindrome Words in a Sentence in Python

Below are the ways to sort all the palindromic words in a given sentence:

Method #1: Using Sort() function (Static input)

Approach:

  • Give the sentence/string as static input and store it in a variable.
  • Convert the given sentence to a list of words using list() and split() functions and store it another variable.
  • Take an empty list to say palindromicwordslist that stores all the palindromic words in the given string and initialize it to null/empty using the list() function or [].
  • Traverse the given list of words using a for loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then append this word to the palindromicwordslist using the append() function.
  • Sort the palindromicwordslist using the sort() function.
  • Take a variable say tempo and initialize its value to 0(Here it acts as a pointer to palindromicwordslist ).
  • Traverse the list of words of the given sentence using the For loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then modify the word with the palindromicwordslist[tempo] word.
  • Increment the tempo value by 1.
  • Convert this list of words of the given sentence to the string using the join() function.
  • Print the final string after sorting the palindromic words.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as static input and store it in a variable.
gvnstrng = 'sos how are you madam pip instal'
# Convert the given sentence to a list of words using list()
# and split() functions and store it another variable.
strngwrdslst = list(gvnstrng.split())
# Take an empty list to say palindromicwordslist
# that stores all the palindromic words in the given string
# and initialize it to null/empty using the list() function or [].
palindromicwordslist = []
# Traverse the given list of words using a for loop.
for wrd in strngwrdslst:
        # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(wrd == wrd[::-1]):
        # If it is true then append this word to the palindromicwordslist
        # using the append() function.
        palindromicwordslist.append(wrd)

# Sort the palindromicwordslist using the sort() function.
palindromicwordslist.sort()
# Take a variable say tempo and initialize its value to 0
# (Here it acts as a pointer to palindromicwordslist ).
tempo = 0
# Traverse the list of words of the given sentence using the For loop.
for wrditr in range(len(strngwrdslst)):
  # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(strngwrdslst[wrditr] == strngwrdslst[wrditr][::-1]):
        # If it is true then modify the word with the palindromicwordslist[tempo] word.
        strngwrdslst[wrditr] = palindromicwordslist[tempo]
        tempo = tempo+1
        # Increment the tempo value by 1.


# Convert this list of words of the given sentence
# to the string using the join() function.
finalstrng = ' '.join(strngwrdslst)
print('The given string before sorting all the palindromic words is = ', gvnstrng)
# Print the final string after sorting the palindromic words.
print('The final string after sorting all the palindromic words is = ', finalstrng)

Output:

The given string before sorting all the palindromic words is =  sos how are you madam pip instal
The final string after sorting all the palindromic words is =  madam how are you pip sos instal

Method #2:Using Sort() function (User input)

Approach:

  • Give the sentence/string as user input using the input() function and store it in a variable.
  • Convert the given sentence to a list of words using list() and split() functions and store it another variable.
  • Take an empty list to say palindromicwordslist that stores all the palindromic words in the given string and initialize it to null/empty using the list() function or [].
  • Traverse the given list of words using a for loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then append this word to the palindromicwordslist using the append() function.
  • Sort the palindromicwordslist using the sort() function.
  • Take a variable say tempo and initialize its value to 0(Here it acts as a pointer to palindromicwordslist ).
  • Traverse the list of words of the given sentence using the For loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then modify the word with the palindromicwordslist[tempo] word.
  • Increment the tempo value by 1.
  • Convert this list of words of the given sentence to the string using the join() function.
  • Print the final string after sorting the palindromic words.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as user input using input() function
# and store it in a variable.
gvnstrng = input('Enter some random string = ')
# Convert the given sentence to a list of words using list()
# and split() functions and store it another variable.
strngwrdslst = list(gvnstrng.split())
# Take an empty list to say palindromicwordslist
# that stores all the palindromic words in the given string
# and initialize it to null/empty using the list() function or [].
palindromicwordslist = []
# Traverse the given list of words using a for loop.
for wrd in strngwrdslst:
        # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(wrd == wrd[::-1]):
        # If it is true then append this word to the palindromicwordslist
        # using the append() function.
        palindromicwordslist.append(wrd)

# Sort the palindromicwordslist using the sort() function.
palindromicwordslist.sort()
# Take a variable say tempo and initialize its value to 0
# (Here it acts as a pointer to palindromicwordslist ).
tempo = 0
# Traverse the list of words of the given sentence using the For loop.
for wrditr in range(len(strngwrdslst)):
  # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(strngwrdslst[wrditr] == strngwrdslst[wrditr][::-1]):
        # If it is true then modify the word with the palindromicwordslist[tempo] word.
        strngwrdslst[wrditr] = palindromicwordslist[tempo]
        tempo = tempo+1
        # Increment the tempo value by 1.


# Convert this list of words of the given sentence
# to the string using the join() function.
finalstrng = ' '.join(strngwrdslst)
print('The given string before sorting all the palindromic words is = ', gvnstrng)
# Print the final string after sorting the palindromic words.
print('The final string after sorting all the palindromic words is = ', finalstrng)

Output:

Enter some random string = the good is madam aba dad mom din cac
The given string before sorting all the palindromic words is = the good is madam aba dad mom din cac
The final string after sorting all the palindromic words is = the good is aba cac dad madam din mom

 Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Sort Palindrome Words in a Sentence Read More »

Program to Check if two Lines are Parallel or Not

Python Program to Check if two Lines are Parallel or Not

In the previous article, we have discussed Python Program to Find the Greatest Digit in a Number.
Parallel Lines :

If two lines remain the same distance apart along their entire length, they are said to be parallel. They will not meet no matter how far you stretch them. These lines are denoted by the equations ax+by=c.

The line equation is ax+by=c, where an is the x coefficient and b is the y coefficient. If the slopes of two lines are equal, we say they are parallel. As a result, we must determine the slope, which is “rise over run.”

The straight-line equation is y=mx+c, where m is the slope. Take a1,b1,c1 and a2,b2,c2 from the user and see if they are parallel.

Given the values of equations of two lines, and the task is to check if the given two lines are parallel or not.

Examples:

Example 1:

Input:

a1=4, b1=8, c1=13
a2=2, b2=4, c2=7

Output:

The given lines are parallel to each other

Example 2:

Input:

a1=8, b1=0, c1=9
a2=8, b2=0, c2=11

Output:

The given lines are parallel to each other

Program to Check if two Lines are Parallel or Not

Below are the ways to check if the given two lines are parallel or not.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the values of a1,b1,c1 as static input and store it in three separate variables.
  • Give the values of a2,b2,c2 as static input and store it in three separate variables.
  • We can Check if the slopes of the given two lines are equal by formula (a1/b1 == a2/b2).
  • Create a function checkParallel() which accepts the 6 parameters (First and second line x,y,z coordinates)
  • Inside the checkParallel() function.
  • Check if both lines y coordinates are not equal to 0 using the If conditional Statement.
  • If it is true then check a1/b1 is equal to a2/b2 using another Nested If conditional Statement.
  • If it is true then return True
  • Else return False.
  • If parent If conditional statement is false then inside the else statement check if first line and second line x and y coordinates are equal or not using the nested If conditional statement.
  • If it is true then return True else return False.
  • Pass the a1,b1,c1,a2,b2,c2 as the arguments to checkParallel() function inside the if Conditional statement.
  • If it is true then print those lines are parallel.
  • Else they are not parallel.
  • The Exit of the Program.

Below is the implementation:

#Create a function checkParallel() which accepts the 6 parameters
#(First and second line x,y,z coordinates)
#We can Check if the slopes of the given two lines are equal by formula (a1/b1 == a2/b2).
def checkParallel(a1,b1,c1,a2,b2,c2):
    #Inside the checkParallel() function.
    #Check if both lines y coordinates are not equal to 0 
    #using the If conditional Statement.
    if(b1!=0 and b2!=0):
        #If it is true then check a1/b1 is equal to a2/b2 
        #using another Nested If conditional Statement.
        if(a1/b1==a2/b2):
            #If it is true then return True
            return True
        else:
            #Else return False.
            return False
    #If parent If conditional statement is false then inside the else statement 
    
    else:
      #check if first line and second line x and y coordinates are equal
      #or not using the nested If conditional statement.
      if(a1==a2 and b1==b2):
     	 #If it is true then return True else return False.
          return True
      else:
          return False
#Give the values of a1,b1,c1  as static input 
#and store it in three separate variables.
a1,b1,c1=4,8,13
#Give the values of a2,b2,c2  as static input 
#and store it in three separate variables.
a2,b2,c2=2,4,7
#Pass the a1,b1,c1,a2,b2,c2 as the arguments to checkParallel() function
#inside the if Conditional statement.
if(checkParallel(a1,b1,c1,a2,b2,c2)):
  #If it is true then print those lines are parallel.
  print('The given lines are parallel to each other')
else:
  #Else they are not parallel.
  print('The given lines are not parallel to each other')

Output:

The given lines are parallel to each other

Method #2: Using For Loop (User Input)

Approach:

  • Give the values of a1,b1,c1 as user input using map(),int(),split() functions and store it in three separate variables.
  • Give the values of a2,b2,c2 as user input using map(),int(),split() functions and store it in three separate variables.
  • We can Check if the slopes of the given two lines are equal by formula (a1/b1 == a2/b2).
  • Create a function checkParallel() which accepts the 6 parameters (First and second line x,y,z coordinates)
  • Inside the checkParallel() function.
  • Check if both lines y coordinates are not equal to 0 using the If conditional Statement.
  • If it is true then check a1/b1 is equal to a2/b2 using another Nested If conditional Statement.
  • If it is true then return True
  • Else return False.
  • If parent If conditional statement is false then inside the else statement check if first line and second line x and y coordinates are equal or not using the nested If conditional statement.
  • If it is true then return True else return False.
  • Pass the a1,b1,c1,a2,b2,c2 as the arguments to checkParallel() function inside the if Conditional statement.
  • If it is true then print those lines are parallel.
  • Else they are not parallel.
  • The Exit of the Program.

Below is the implementation:

#Create a function checkParallel() which accepts the 6 parameters
#(First and second line x,y,z coordinates)
#We can Check if the slopes of the given two lines are equal by formula (a1/b1 == a2/b2).
def checkParallel(a1,b1,c1,a2,b2,c2):
    #Inside the checkParallel() function.
    #Check if both lines y coordinates are not equal to 0 
    #using the If conditional Statement.
    if(b1!=0 and b2!=0):
        #If it is true then check a1/b1 is equal to a2/b2 
        #using another Nested If conditional Statement.
        if(a1/b1==a2/b2):
            #If it is true then return True
            return True
        else:
            #Else return False.
            return False
    #If parent If conditional statement is false then inside the else statement 
    
    else:
      #check if first line and second line x and y coordinates are equal
      #or not using the nested If conditional statement.
      if(a1==a2 and b1==b2):
          #If it is true then return True else return False.
          return True
      else:
          return False
#Give the values of a1,b1,c1 as user input using map(),int(),split() functions 
#and store it in three separate variables.
a1,b1,c1=map(int,input('Enter some random x y z coordinates separated by spaces = ').split())                    
#Give the values of a2,b2,c2 as user input using map(),int(),split() functions 
#and store it in three separate variables.
a2,b2,c2=map(int,input('Enter some random x y z coordinates separated by spaces = ').split())
#Pass the a1,b1,c1,a2,b2,c2 as the arguments to checkParallel() function
#inside the if Conditional statement.
if(checkParallel(a1,b1,c1,a2,b2,c2)):
  #If it is true then print those lines are parallel.
  print('The given lines are parallel to each other')
else:
  #Else they are not parallel.
  print('The given lines are not parallel to each other')

Output:

Enter some random x y z coordinates separated by spaces = 8 0 9
Enter some random x y z coordinates separated by spaces = 8 0 11
The given lines are parallel to each other

They are parallel to each other

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Check if two Lines are Parallel or Not Read More »

Program to invert a Dictionary

Python Program to invert a Dictionary

In the previous article, we have discussed Python Program to Check if two Lines are Parallel or Not
Dictionary in python:

Python includes a class dictionary, which is typically defined as a set of key-value pairs. In Python, inverting a dictionary means swapping the key and value in the dictionary.

One thing is certain: complexity can be found in all of the different ways of storing key-value pairs. That is why dictionaries are used.

Python dictionaries are mutable collections of things that contain key-value pairs. The dictionary contains two main components: keys and values. These keys must be single elements, and the values can be of any data type, such as list, string, integer, tuple, and so on. The keys are linked to their corresponding values. In other words, the values can be retrieved using their corresponding keys.

A dictionary is created in Python by enclosing numerous key-value pairs in curly braces.

For example :

dictionary ={‘monday’:1, ‘tuesday’:2, ‘wednesday’:3}

The output after inverting the dictionary is { 1: [‘monday’] , 2: [‘tuesday’] , 3: [‘wednesday’] }

Given a dictionary, and the task is to invert the given dictionary.

Examples:

Example1:

Input:

Given dictionary = {10: 'jan', 20: 'feb', 30: 'march', 40: 'April', 50: 'may'}

Output:

The inverse of the given dictionary =  {'jan': [10], 'feb': [20], 'march': [30], 'April': [40], 'may': [50]}

Example 2:

Input:

Given dictionary = {'monday': 1, 'tuesday': 2, 'wednesday': 3}

Output:

The inverse of the given dictionary = {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Program to invert a Dictionary in Python

Below are the ways to invert a given dictionary

Method #1: Using For Loop (Static Input)

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {'monday': 1, 'tuesday': 2, 'wednesday': 3}
# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

The inverse of the given dictionary =  {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Method #2: Using For Loop (User Input)

Approach:

  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = {}
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee = input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee

# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

Enter some random number of keys of the dictionary = 5
Enter key and value separated by spaces = hello 785
Enter key and value separated by spaces = this 100
Enter key and value separated by spaces = is 900
Enter key and value separated by spaces = btechgeeks 500
Enter key and value separated by spaces = python 400
The inverse of the given dictionary = {'785': ['hello'], '100': ['this'], '900': ['is'], '500': ['btechgeeks'], '400': ['python']}

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to invert a Dictionary Read More »

Program Enter ‘’ Between two Identical Characters in a String

Python Program Enter ‘*’ Between two Identical Characters in a String

In the previous article, we have discussed Python Program to invert a Dictionary
Given a String and the task is to enter ‘*’ between two identical characters.

Example :

Given string = btechgeeks

Output: btechge*eks

Explanation: Since both the e’s are identical and next to each other. so, we enter a ‘*’ in between them.

Examples:

Example1:

Input:

Given string = "good morning btechgeekss"

Output:

The given string after entering '*' between two identical characters= go*od morning btechge*eks*

Example 2:

Input:

Given string = "aabcddeefghii"

Output:

The given string after entering '*' between two identical characters= a*abcd*de*efghi*

Program Enter ‘*’ Between two Identical Characters in a String

Below are the ways to enter ‘*’ between two identical characters in a given String.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a new empty string say ‘new_str’and store it in another variable.
  • Take a variable and initialize its value with ‘0’ and store it in another variable.
  • Loop from ‘0’ to the length of the given string -1 using for loop and len() function.
  • Concat the new_str with the iterator value of the given string and store it in the same variable ‘new_str’.
  • Check if the iterator value of the given input string is equal to the iterator+1 value of the given input string using the if conditional statement.
  • If the statement is true, concatenate the ‘new_str’ with the ‘*’ symbol and store it in the same variable ‘new_str’.
  • Print the variable ‘new_str’ to enter ‘*’ between two identical characters in a given String.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "good morning btechgeekss"
# Take a new empty string say 'new_str'and store it in another variable.
new_str = ""
# Take a variable and initialize its value with '0' and store it in another variable.
itr = 0
# Loop from '0' to the length of the given string -1 using for loop and len() function.
for itr in range(0, len(gvn_str)-1):
    # Concat the new_str with the iterator value of the given string and
    # store it in the same variable 'new_str'
    new_str = new_str + gvn_str[itr]
# Check if the iterator value of the given input string is equal to the iterator+1 value
# of the given input string using the if conditional statement.
    if(gvn_str[itr] == gvn_str[itr+1]):
      # If the statement is true, concat the 'new_str' with the '*' symbol and
      # store it in the same variable 'new_str'.
        new_str += '*'
# Print the variable 'new_str' to enter '*' between two identical characters in a
# given String.
print("The given string after entering '*' between two identical characters=", new_str)

Output:

The given string after entering '*' between two identical characters= go*od morning btechge*eks*

Method #2: Using For Loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take a new empty string say ‘new_str’and store it in another variable.
  • Take a variable and initialize its value with ‘0’ and store it in another variable.
  • Loop from ‘0’ to the length of the given string -1 using for loop and len() function.
  • Concat the new_str with the iterator value of the given string and store it in the same variable ‘new_str’.
  • Check if the iterator value of the given input string is equal to the iterator+1 value of the given input string using the if conditional statement.
  • If the statement is true, concatenate the ‘new_str’ with the ‘*’ symbol and store it in the same variable ‘new_str’.
  • Print the variable ‘new_str’ to enter ‘*’ between two identical characters in a given String.
  • 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 = ")
# Take a new empty string say 'new_str'and store it in another variable.
new_str = ""
# Take a variable and initialize its value with '0' and store it in another variable.
itr = 0
# Loop from '0' to the length of the given string -1 using for loop and len() function.
for itr in range(0, len(gvn_str)-1):
    # Concat the new_str with the iterator value of the given string and
    # store it in the same variable 'new_str'
    new_str = new_str + gvn_str[itr]
# Check if the iterator value of the given input string is equal to the iterator+1 value
# of the given input string using the if conditional statement.
    if(gvn_str[itr] == gvn_str[itr+1]):
      # If the statement is true, concat the 'new_str' with the '*' symbol and
      # store it in the same variable 'new_str'.
        new_str += '*'
# Print the variable 'new_str' to enter '*' between two identical characters in a
# given String.
print("The given string after entering '*' between two identical characters=", new_str)

Output:

Enter some random string = aabcddeefghii
The given string after entering '*' between two identical characters= a*abcd*de*efghi*

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program Enter ‘*’ Between two Identical Characters in a String Read More »