Python Program to Take in a String and Replace Every Blank Space with Hyphen

Program to Take in a String and Replace Every Blank Space with Hyphen

Strings in Python:

A string is one of the most frequent data types in any computer language. A string is a collection of characters that can be used to represent usernames, blog posts, tweets, or any other text content in your code. You can make a string and assign it to a variable by doing something like this.

given_string='btechgeeks'

Strings are considered immutable in Python, once created, they cannot be modified. You may, however, construct new strings from existing strings using a variety of approaches. This form of programming effort is known as string manipulation.

Examples:

Example1:

Input:

given string = hello this is BtechGeeks

Output:

The original string before modification = hello this is BtechGeeks
The new string after modification = hello-this-is-BtechGeeks

Example2:

Input:

given string = files will be upload to a folder you can read those files in the program folder

Output:

Enter some random string = files will be upload to a folder you can read those files in the program folder
The original string before modification = files will be upload to a folder you can read those files in the program folder
The new string after modification = files-will-be-upload-to-a-folder-you-can-read-those-files-in-the-program-folder

Program to Take in a String and Replace Every Blank Space with Hyphen

Below are the ways to scan the string and replace every blank space with a hyphen in Python.

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

Method #1:Using replace function (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Using the replace function replace all blank space with a hyphen by providing blank space as the first argument and hyphen as the second argument in replace function.
  • Print the modified string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
given_string = 'hello this is BtechGeeks'
# printing the original string before modification
print('The original string before modification =', given_string)
# Using the replace function replace all blank space with a hyphen by providing blank space as the first argument
# and hyphen as the second argument in replace function.
modified_string = given_string.replace(' ', '-')
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

The original string before modification = hello this is BtechGeeks
The new string after modification = hello-this-is-BtechGeeks

Method #2:Using replace function (User Input)

Approach:

  • Give the string as user input using the int(input()) function and store it in a variable.
  • Using the replace function replace all blank space with a hyphen by providing blank space as the first argument and hyphen as the second argument in replace function.
  • Print the modified string.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using int(input()) function and store it in a variable.
given_string = input('Enter some random string = ')
# printing the original string before modification
print('The original string before modification =', given_string)
# Using the replace function replace all blank space with a hyphen by providing blank space as the first argument
# and hyphen as the second argument in replace function.
modified_string = given_string.replace(' ', '-')
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

Enter some random string = files will be upload to a folder you can read those files in the program folder
The original string before modification = files will be upload to a folder you can read those files in the program folder
The new string after modification = files-will-be-upload-to-a-folder-you-can-read-those-files-in-the-program-folder

The replace() function replaces all instances of ” with ‘-‘.

Python Program to Form a New String where the First Character and the Last Character have been Exchanged

Program to Form a New String where the First Character and the Last Character have been Exchanged

Strings in Python:

A string is one of the most frequent data types in any computer language. A string is a collection of characters that can be used to represent usernames, blog posts, tweets, or any other text content in your code. You can make a string and assign it to a variable by doing something like this.

given_string='btechgeeks'

Strings are considered immutable in Python, once created, they cannot be modified. You may, however, construct new strings from existing strings using a variety of approaches. This form of programming effort is known as string manipulation.

Examples:

Example1:

Input:

given string =  hello this is btechgeeks

Output:

The original string before modification = hello this is btechgeeks
The new string after modification = sello this is btechgeekh

Example2:

Input:

given string = this is btechgeeks online coding platform for geeks

Output:

Enter some random string = this is btechgeeks online coding platform for geeks
The original string before modification = this is btechgeeks online coding platform for geeks
The new string after modification = shis is btechgeeks online coding platform for geekt

Program to Form a New String where the First Character and the Last Character have been Exchanged

Below are the ways to form a new string in which the first and last characters have been swapped

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

1)Using slicing(static input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a function that swaps the first and last character of the string.
  • Pass the given string as an argument to the function.
  • Split the string in the function.
  • The last character is then added to the middle half of the string, which is then added to the first character.
  • The modified string will be returned.
  • Print the modified string
  • The Exit of the program.

Below is the implementation :

# Take a function that swaps the first and last character of the string.
def swapString(given_string):
    # Split the string in the function.
    # The last character is then added to the middle half of the string,
    # which is then added to the first character.
    modifiedstring = given_string[-1:] + given_string[1:-1] + given_string[:1]
    # The modified string will be returned.
    return modifiedstring


# Give the string as static input and store it in a variable.
given_string = 'hello this is btechgeeks'
# printing the original string before modification
print('The original string before modification =', given_string)
# Pass the given string as an argument to the function.
modified_string = swapString(given_string)
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

The original string before modification = hello this is btechgeeks
The new string after modification = sello this is btechgeekh

Explanation:

  • Give the string as static input and store it in a variable.
  • This string is supplied to a function as an argument.
  • Using string slicing, the string is split into three parts in the function: the last character, the middle part, and the first character.
  • The ‘+’ operator is then used to concatenate these three parts.
  • After that, the modified string is printed.

2)Using slicing(User input)

Approach:

  • Give the string as user input using int(input()) and store it in a variable.
  • Take a function that swaps the first and last character of the string.
  • Pass the given string as an argument to the function.
  • Split the string in the function.
  • The last character is then added to the middle half of the string, which is then added to the first character.
  • The modified string will be returned.
  • Print the modified string
  • The Exit of the program.

Below is the implementation :

# Take a function that swaps the first and last character of the string.
def swapString(given_string):
    # Split the string in the function.
    # The last character is then added to the middle half of the string,
    # which is then added to the first character.
    modifiedstring = given_string[-1:] + given_string[1:-1] + given_string[:1]
    # The modified string will be returned.
    return modifiedstring


# Give the string as user input using int(input()) and store it in a variable.
given_string = input('Enter some random string = ')
# printing the original string before modification
print('The original string before modification =', given_string)
# Pass the given string as an argument to the function.
modified_string = swapString(given_string)
# printing the new string after modification
print('The new string after modification =', modified_string)

Output:

Enter some random string = this is btechgeeks online coding platform for geeks
The original string before modification = this is btechgeeks online coding platform for geeks
The new string after modification = shis is btechgeeks online coding platform for geekt

Related Programs:

Python Program to Implement the Latin Alphabet Cipher

Python Program to Implement the Latin Alphabet Cipher

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

We will learn how to use Python to implement the Latin Alphabet Cipher.

The Latin Alphabet Cipher Encryption Technique is one of the quickest and most straightforward methods of encoding data. It’s essentially a replacement cipher method, in which each letter of a given input is replaced by its matching number as represented alphabetically.

Examples:

Example1:

Input:

Given string =Hello this is BTechGeeks

Output:

The encrypted message of the given string{ Hello this is BTechGeeks }is :
8 5 12 12 15  
20 8 9 19  
9 19  
2 20 5 3 8 7 5 5 11 19

Example2:

Input:

Given string = btechgeeks python

Output:

The encrypted message of the given string{ btechgeeks python }is :
2 20 5 3 8 7 5 5 11 19 
16 25 20 8 15 14

Python Program to Implement the Latin Alphabet Cipher in Python

Below are the ways to implement the Latin Alphabet Cipher in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input(which consists of only alphabets and spaces) and store it in a variable
  • Iterate through the characters of the string using For loop.
  • We can calculate the ASCII value of the character using the ord() function.
  • Now, transform each input string character to its ASCII value and subtract it from the ASCII value of alphabet A for uppercase characters and ‘a’ for lowercase ones.
  • The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
  • ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
  • If the character is space then print it(That is printing space character without endl which makes it to print in next line)
  • The Exit of the program.

Below is the implementation:

# Give the string as static input(which consists of only alphabets and spaces) and store it in a variable
givenstring = "Hello this is BTechGeeks"
print('The encrypted message of the given string{', givenstring, '}is :')
# Iterate through the characters of the string using For loop.
# We can calculate the ASCII value of the character using the ord() function.
for m in givenstring:
    # Now, transform each input string character to its ASCII value
    # and subtract it from the ASCII
    # value of alphabet A for uppercase characters and 'a' for lowercase ones.
    if (m >= "A" and m <= "Z"):
      # The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
        print(ord(m)-ord("A")+1, end=" ")
    elif (m >= "a" and m <= 'z'):
        # ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
        print(ord(m)-ord("a")+1, end=" ")
    # If the character is space then print it(That is printing
    # space character without endl which makes it to print in next line)
    if m == (" "):
        print(m)

Output:

The encrypted message of the given string{ Hello this is BTechGeeks }is :
8 5 12 12 15  
20 8 9 19  
9 19  
2 20 5 3 8 7 5 5 11 19

Method #2: Using For Loop (User Input)

Approach:

  • Give the string as user input(which consists of only alphabets and spaces) using input() and store it in a variable.
  • Iterate through the characters of the string using For loop.
  • We can calculate the ASCII value of the character using the ord() function.
  • Now, transform each input string character to its ASCII value and subtract it from the ASCII value of alphabet A for uppercase characters and ‘a’ for lowercase ones.
  • The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
  • ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
  • If the character is space then print it(That is printing space character without endl which makes it to print in next line)
  • The Exit of the program.

Below is the implementation:

# Give the string as user input(which consists of only alphabets and spaces)
# using input() and store it in a variable.
givenstring = input('Enter some random string = ')
print('The encrypted message of the given string{', givenstring, '}is :')
# Iterate through the characters of the string using For loop.
# We can calculate the ASCII value of the character using the ord() function.
for m in givenstring:
    # Now, transform each input string character to its ASCII value
    # and subtract it from the ASCII
    # value of alphabet A for uppercase characters and 'a' for lowercase ones.
    if (m >= "A" and m <= "Z"):
      # The operation is written as ord(givenstring[i])-ord(“A”)+1 for uppercase letters.
        print(ord(m)-ord("A")+1, end=" ")
    elif (m >= "a" and m <= 'z'):
        # ord(givenstring[i])-ord(“a”)+1 for lowercase letters.
        print(ord(m)-ord("a")+1, end=" ")
    # If the character is space then print it(That is printing
    # space character without endl which makes it to print in next line)
    if m == (" "):
        print(m)

Output:

Enter some random string = btechgeeks python
The encrypted message of the given string{ btechgeeks python }is :
2 20 5 3 8 7 5 5 11 19 
16 25 20 8 15 14

Related Programs:

Python Program to Create a Class and Compute the Area and the Perimeter of the Circle

Program to Create a Class and Compute the Area and the Perimeter of the Circle

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Object-Oriented Programming(OOPS):

Object-Oriented Programming (OOP) is a programming paradigm based on the concepts of classes and objects. It is used to organize a software program into simple, reusable code blueprints (typically referred to as classes), which are then used to build individual instances of objects. Object-oriented programming languages include JavaScript, C++, Java, and Python, among others.

A class is a generic blueprint that can be used to generate more specific, concrete things. Classes are frequently used to represent broad groups, such as Cars or Dogs, that share property. These classes indicate what properties, such as color, an instance of this type will have, but not the value of those attributes for a specific object.

An object comprises data, such as the raw or preprocessed materials at each step of an assembly line, as well as behavior, such as the action performed by each assembly line component.

Python, like other general-purpose programming languages, has always been an object-oriented language. It enables us to create a program with an Object-Oriented approach. Classes and objects are simple to build and utilize in Python.

Given the radius of the circle, the task is to write the python program using classes that calculate the area and perimeter of the circle.

Examples:

Example1:

Input:

given radius = 13.5

Output:

The Perimeter of circle with given radius 13.5 = 84.823
The Area of circle with given radius 13.5 = 572.5553

Example2:

Input:

given radius = 20.98

Output:

The Perimeter of circle with given radius 20.98 = 131.8212
The Area of circle with given radius 20.98 = 1382.8047

Program to Create a Class and Compute the Area and the Perimeter of the Circle

Below is the full approach for writing a Python program that creates a class with two methods that calculate the area and perimeter of the circle.

1)Using Classes(Static Input)

Approach:

  • Give the radius of the circle as static input and store it in a variable.
  • Create a class and use a parameterized constructor to initialize its value (radius of the circle).
  • Create two methods inside the class.
  • printPerimeter: which calculates the perimeter of the circle and returns it.
  • printArea: which calculates the area of the circle and returns it.
  • Create an object to represent the class.
  • Call both methods with the object created above.
  • Hence the area and perimeter of the circle are calculated and printed.
  • The Exit of the Program.

Below is the implementation:

# importing math module
import math
# creating a class


class circleClass():
  # use a parameterized constructor to initialize its value (radius of the circle).
    def __init__(self, circleradius):
        self.circleradius = circleradius
    # Create two methods inside the class.
    # printArea: which calculates the area of the circle and returns it.

    def printArea(self):
        return math.pi*(self.circleradius**2)
     # printPerimeter: which calculates the perimeter of the circle and returns it.

    def printPerimeter(self):
        return 2*math.pi*self.circleradius


# Give the radius of the circle as static input and store it in a variable.
circleradius = 13.5
# Create an object to represent the class.
circleobj = circleClass(circleradius)
# Call both methods with the object created above.
# Hence the area and perimeter of the circle are calculated and printed.
print("The Perimeter of circle with given radius",
      circleradius, '=', round(circleobj.printPerimeter(), 4))
print("The Area of circle with given radius", circleradius,
      '=', round(circleobj.printArea(), 4))

Output:

The Perimeter of circle with given radius 13.5 = 84.823
The Area of circle with given radius 13.5 = 572.5553

Explanation:

  • The radius value must be given as static input from the user.
  • A circle class is created, and the __init__() method is used to initialize the class’s values (radius of the circle.
  • The area method returns math. pi*(self. radius**2), which is the class’s area.
  • Another method, perimeter, returns 2*math. pi*self. radius, which represents the class’s perimeter.
  • The class’s object is created.
  • The methods printArea() and printPerimeter() are called using the object.
  • The area and perimeter of the circle are printed.

2)Using Classes(User Input)

Approach:

  • Give the radius of the circle as user input using float(input()) and store it in a variable.
  • Create a class and use a parameterized constructor to initialize its value (radius of the circle).
  • Create two methods inside the class.
  • printPerimeter: which calculates the perimeter of the circle and returns it.
  • printArea: which calculates the area of the circle and returns it.
  • Create an object to represent the class.
  • Call both methods with the object created above.
  • Hence the area and perimeter of the circle are calculated and printed.
  • The Exit of the Program.

Below is the implementation:

# importing math module
import math
# creating a class


class circleClass():
  # use a parameterized constructor to initialize its value (radius of the circle).
    def __init__(self, circleradius):
        self.circleradius = circleradius
    # Create two methods inside the class.
    # printArea: which calculates the area of the circle and returns it.

    def printArea(self):
        return math.pi*(self.circleradius**2)
     # printPerimeter: which calculates the perimeter of the circle and returns it.

    def printPerimeter(self):
        return 2*math.pi*self.circleradius


# Give the radius of the circle as user input using float(input()) and store it in a variable.
circleradius = float(input('Enter some random radius of the circle = '))
# Create an object to represent the class.
circleobj = circleClass(circleradius)
# Call both methods with the object created above.
# Hence the area and perimeter of the circle are calculated and printed.
print("The Perimeter of circle with given radius",
      circleradius, '=', round(circleobj.printPerimeter(), 4))
print("The Area of circle with given radius", circleradius,
      '=', round(circleobj.printArea(), 4))

Output:

Enter some random radius of the circle = 20.98
The Perimeter of circle with given radius 20.98 = 131.8212
The Area of circle with given radius 20.98 = 1382.8047

Related Programs:

Python Program to Remove the First Occurrence of Character in a String

Program to Remove the First Occurrence of Character in a String

In this article, we’ll learn how to use Python to remove the first occurrence of a character in a string. The aim is to remove the first occurrence of a character in a string. To begin, locate the character in the string and confirm that it is the first occurrence. Finally, remove the character from the string and display the result.

Examples:

Example1:

Input:

Given String =goodmorningthisisbtechgeekspython
Given Character =s

Output:

The Given string after removing first occurence of the character [ s ] is goodmorningthisisbtechgeekspython
The Given string after removing first occurence of the character [ s ] is goodmorningthiisbtechgeekspython

Example2:

Input:

Given String =hellothisisbtechgeeks
Given Character =e

Output:

The Given string after removing first occurence of the character [ e ] is hellothisisbtechgeeks
The Given string after removing first occurence of the character [ e ] is hllothisisbtechgeeks

Program to Remove the First Occurrence of Character in a String in Python

Below are the ways to remove the first occurrence of the given character in a string in Python.

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 string as static input and store it in a variable.
  • Give the character as static input and store it in another variable.
  • Calculate the length of the string using the len() function.
  • Loop in the characters of the string using the For loop.
  • Check if the iterator character is equal to the given character using the if conditional statement and == operator.
  • Initialize the resultstrng with the given string from 0 to iterator value concatenated with iterator value +1 to the length of the given string.
  • Break the For loop using the break keyword.
  • Print the Result.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvnstrng = 'hellothisisbtechgeeks'
# Give the character as static input and store it in another variable.
gvnchar = 'e'
# Calculate the length of the string using the len() function.
strnglength = len(gvnstrng)
# Loop in the characters of the string using the For loop.
for i in range(strnglength):
  # Check if the iterator character is equal to the given character
  # using the if conditional statement and == operator.
    if(gvnstrng[i] == gvnchar):
      # Initialize the resultstrng with the given string
      # from 0 to iterator value concatenated
      # with iterator value +1 to the length of the given string.
        reesultvalu = gvnstrng[0:i] + gvnstrng[i + 1:strnglength]
        # Break the For loop using the break keyword.
        break
# Print the Result.
print(
    'The Given string after removing first occurence of the character [', gvnchar, '] is', gvnstrng)
print(
    'The Given string after removing first occurence of the character [', gvnchar, '] is', reesultvalu)

Output:

The Given string after removing first occurence of the character [ e ] is hellothisisbtechgeeks
The Given string after removing first occurence of the character [ e ] is hllothisisbtechgeeks

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 character as user input using the input() function and store it in another variable.
  • Calculate the length of the string using the len() function.
  • Loop in the characters of the string using the For loop.
  • Check if the iterator character is equal to the given character using the if conditional statement and == operator.
  • Initialize the resultstrng with the given string from 0 to iterator value concatenated with iterator value +1 to the length of the given string.
  • Break the For loop using the break keyword.
  • Print the Result.
  • 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.
gvnstrng = input('Enter some random given string = ')
# Give the character as user input using the input() function and store it in another variable.
gvnchar = input('Enter some random character = ')
# Calculate the length of the string using the len() function.
strnglength = len(gvnstrng)
# Loop in the characters of the string using the For loop.
for i in range(strnglength):
  # Check if the iterator character is equal to the given character
  # using the if conditional statement and == operator.
    if(gvnstrng[i] == gvnchar):
      # Initialize the resultstrng with the given string
      # from 0 to iterator value concatenated
      # with iterator value +1 to the length of the given string.
        reesultvalu = gvnstrng[0:i] + gvnstrng[i + 1:strnglength]
        # Break the For loop using the break keyword.
        break
# Print the Result.
print(
    'The Given string after removing first occurence of the character [', gvnchar, '] is', gvnstrng)
print(
    'The Given string after removing first occurence of the character [', gvnchar, '] is', reesultvalu)

Output:

Enter some random given string = goodmorningthisisbtechgeekspython
Enter some random character = s
The Given string after removing first occurence of the character [ s ] is goodmorningthisisbtechgeekspython
The Given string after removing first occurence of the character [ s ] is goodmorningthiisbtechgeekspython

Related Programs:

Python Program to Create a Class in which One Method Accepts a String from the User and Another Prints it

Program to Create a Class in which One Method Accepts a String from the User and Another Prints it

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Object-Oriented Programming(OOPS):

Object-oriented programming (OOP) is a form of program structure that involves grouping related characteristics and activities into separate objects.

Objects are conceptually similar to system components. Consider a program to be a sort of factory assembly line. A system component processes some material at each step of the assembly line, eventually changing raw material into a finished product.

An object comprises data, such as the raw or preprocessed materials at each step of an assembly line, as well as behavior, such as the action performed by each assembly line component.

Python, like other general-purpose programming languages, has always been an object-oriented language. It enables us to create a program with an Object-Oriented approach. Classes and objects are simple to build and utilize in Python.

Using classes and objects, an object-oriented paradigm is used to construct the code. The object is associated with real-world entities such as a book, a house, a pencil, and so on. The oops notion is concerned with building reusable code. It is a common strategy for solving problems by constructing objects.

The task is to write a Python program that creates a class with one method that accepts a string from the user and another that prints it.

Examples:

Example1:

Input:

Enter some random string = btechgeeks

Output:

The string = btechgeeks

Example2:

Input:

Enter some random string = samokestring

Output:

The string = samokestring

Program to Create a Class in which One Method Accepts a String from the User and other Prints it in Python

Below is the full approach for writing a Python program that creates a class with one method that accepts a string from the user and another that prints it.

Approach:

  • Create a class and use the constructor to initialize the class’s values(here it is a string).
  • Create two methods inside the class.
  • getString: which scans the value of the given string.
  • putString: Which prints the value of the given string.
  • Create an object to represent the class.
  • Call both methods with the object created above.
  • Hence the string is scanned and printed.
  • The Exit of the Program.

Below is the implementation:

# creating a class
class stringClass():
  # use the constructor to initialize the class's values(here it is a string).
    def __init__(self):
        self.string = ""
    # Creating two methods inside the class.
    # getString: which scans the value of the given string

    def getString(self):
      # using input() function to scan the value of the string.
        self.string = input("Enter some random string = ")
   # putString: Which prints the value of the given string.

    def putString(self):
      # printing the string
        print("The string  =", self.string)


# Create an object to represent the class.
stringobj = stringClass()
# Call both methods with the object created above.
# calling getString method which scans the value of string
stringobj.getString()
# calling putString method which prints the value of the string
stringobj.putString()

Output:

Enter some random string = btechgeeks
The string = btechgeeks

Explanation:

  • A class called stringClass is created, and the __init__() function is used to set the string’s value to ” “(which is the default constructor in this case).
  • The first method (getString), Scan’s the string’s value from the user using input() function)
  • The second method (putString) is used to print the string’s value.
  • A class object called stringobj is created.
  • The methods getString() and putString() are printed using the object.
  • The string’s value which is scanned using getString is printed using putString.

Related Programs:

Python Program to Print All Permutations of a String in Lexicographic Order without Recursion

Python Program to Print All Permutations of a String in Lexicographic Order without Recursion

Strings in Python:

Strings are simple text in programming, which might be individual letters, words, phrases, or whole sentences. Python strings have powerful text-processing capabilities, such as searching and replacing characters, cutting characters, and changing case. Empty strings are written as two quotations separated by a space. Single or double quotation marks may be used. Three quote characters can be used to easily build multi-line strings.

Given a string ,the task is to print all the permutations of the given string in lexicographic order without using recursion in Python.

Examples:

Example1:

Input:

given string ='hug'

Output:

printing all [ hug ] permutations :
hug
ugh
uhg
ghu
guh
hgu

Example2:

Input:

given string ='tork'

Output:

printing all [ tork ] permutations :
tork
trko
trok
kort
kotr
krot
krto
ktor
ktro
okrt
oktr
orkt
ortk
otkr
otrk
rkot
rkto
rokt
rotk
rtko
rtok
tkor
tkro
tokr

Program to Print All Permutations of a String in Lexicographic Order without Recursion

Below are the ways to Print All string permutations without recursion in lexicographic order:

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

1)Using for and while Loops(Static Input)

Approach:

  • Give the string as static input.
  • The algorithm works by first generating a loop that will run n! times, where n is the length of the string.
  • Each loop iteration produces the string and looks for its next variant to print in the following iteration.
  • The following is the next higher permutation.
  • If we call our sequence seq, we identify the least index p such that all entries in seq[p…end] are in decreasing order.
  • If seq[p…end] represents the whole sequence, i.e. p == 0, then seq is the highest permutation. So we simply reverse the entire string to find the shortest permutation, which we regard to be the next permutation.
  • If p > 0, we reverse seq[p…end].

Below is the implementation:

from math import factorial


def printPermutationsLexico(string):
    # In lexicographic sequence, print all permutations of string s.
    stringseq = list(string)

    # There will be n! permutations where n = len (seq).
    for t in range(factorial(len(stringseq))):
        # print permutation by joining all the characters using join() function
        print(''.join(stringseq))

        # Find p such that seq[per:] is the longest sequence with lexicographic
        # elements in decreasing order.
        per = len(stringseq) - 1
        while per > 0 and stringseq[per - 1] > stringseq[per]:
            per -= 1

        # reverse the stringsequence from per to end using reversed function
        stringseq[per:] = reversed(stringseq[per:])

        if per > 0:
            # Find q such that seq[q] is the smallest element in seq[per:] and seq[q] is greater
            # than seq[p - 1].Find q such that seq[q] is the smallest
            # element in seq[per:] and seq[q] is greater than seq[per - 1].
            q = per
            while stringseq[per - 1] > stringseq[q]:
                q += 1

            # swapping seq[per - 1] and seq[q]
            stringseq[per - 1], stringseq[q] = stringseq[q], stringseq[per - 1]


# given string as static input
given_string = 'hug'
# printing  all the perumutations
print('printing all [', given_string, '] permutations :')
# passing given string to printPermutationsLexico function
printPermutationsLexico(given_string)

Output:

printing all [ hug ] permutations :
hug
ugh
uhg
ghu
guh
hgu

Explanation:

  • User must give string input as static .
  • On the string, the method printPermutationsLexico is called.
  • The function then prints the string’s permutations in lexicographic order.

2)Using for and while Loops(User Input)

Approach:

  • Enter some random string as user input using int(input()) function.
  • The algorithm works by first generating a loop that will run n! times, where n is the length of the string.
  • Each loop iteration produces the string and looks for its next variant to print in the following iteration.
  • The following is the next higher permutation.
  • If we call our sequence seq, we identify the least index p such that all entries in seq[p…end] are in decreasing order.
  • If seq[p…end] represents the whole sequence, i.e. p == 0, then seq is the highest permutation. So we simply reverse the entire string to find the shortest permutation, which we regard to be the next permutation.
  • If p > 0, we reverse seq[p…end].

Below is the implementation:

from math import factorial


def printPermutationsLexico(string):
    # In lexicographic sequence, print all permutations of string s.
    stringseq = list(string)

    # There will be n! permutations where n = len (seq).
    for t in range(factorial(len(stringseq))):
        # print permutation by joining all the characters using join() function
        print(''.join(stringseq))

        # Find p such that seq[per:] is the longest sequence with lexicographic
        # elements in decreasing order.
        per = len(stringseq) - 1
        while per > 0 and stringseq[per - 1] > stringseq[per]:
            per -= 1

        # reverse the stringsequence from per to end using reversed function
        stringseq[per:] = reversed(stringseq[per:])

        if per > 0:
            # Find q such that seq[q] is the smallest element in seq[per:] and seq[q] is greater
            # than seq[p - 1].Find q such that seq[q] is the smallest
            # element in seq[per:] and seq[q] is greater than seq[per - 1].
            q = per
            while stringseq[per - 1] > stringseq[q]:
                q += 1

            # swapping seq[per - 1] and seq[q]
            stringseq[per - 1], stringseq[q] = stringseq[q], stringseq[per - 1]


# Enter some random string as user input using int(input()) function.
given_string =input('Enter some random string = ')
# printing  all the perumutations
print('printing all [', given_string, '] permutations :')
# passing given string to printPermutationsLexico function
printPermutationsLexico(given_string)

Output:

Enter some random string = epic
printing all [ epic ] permutations :
epic
icep
icpe
iecp
iepc
ipce
ipec
pcei
pcie
peci
peic
pice
piec
ceip
cepi
ciep
cipe
cpei
cpie
ecip
ecpi
eicp
eipc
epci

Related Programs:

Python Program to Find the Gravitational Force Acting Between Two Objects

Program to Find the Gravitational Force Acting Between Two Objects

Gravitational Force:

The gravitational force is a force that attracts any two mass-bearing objects. The gravitational force is called attractive because it always strives to pull masses together rather than pushing them apart. In reality, every thing in the cosmos, including you, is tugging on every other item! Newton’s Universal Law of Gravitation is the name for this. You don’t have a significant mass, thus you’re not dragging on those other objects very much. Objects that are extremely far apart do not noticeably pull on each other either. However, the force exists and can be calculated.

Gravitational Force Formula :

Gravitational Force = ( G *  m1 * m2 ) / ( r ** 2 )

Given masses of two objects and the radius , the task is to calculate the Gravitational Force acting between the given two particles in Python.

Examples:

Example1:

Input:

mass1 = 1300012.67
mass2 = 303213455.953
radius = 45.4

Output:

The gravitational force of objects with masses 1300012.67 kg 303213455.953 kg  of radius= 45.4 = 12.761610184592419

Example2:

Input:

Enter the first mass of the object =2491855.892 
Enter the second mass of the object =9000872 
Enter the distance/radius between the objects =50

Output:

The gravitational force of objects with masses 24918552.892 kg 23145689000872.0 kg of radius= 50.0 = 15394799.86164859

Program to Find the Gravitational Force Acting Between Two Objects in Python

We will write the code which calculates the gravitational force acting between the particles and print it

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.

1)Calculating the Gravitational Force  (Static Input)

Approach:

  • Take both the masses and the distance between the masses and store them in different variables  or give input as static
  • One of the variables should be set to the value of the gravitational constant, G.
  • The formula is used to calculate the force between the masses.
  • Print the force value, rounded up to two decimal places.
  • Exit the program.

Below is the implementation:

# given first mass
mass1 = 1300012.67
# given second mass
mass2 = 303213455.953
# enter the radius
radius = 45.4
# Given value of Gravitational Constant Gval
Gval = 6.673*(10**(-11))
# Calculating the value of the gravitational force Gforce
Gforce = (Gval*mass1*mass2)/(radius**2)
# printing the value of gravitational force
print("The gravitational force of objects with masses", str(mass1) +
      " kg "+str(mass2)+" kg ", "of radius=", radius, "=", Gforce)

Output:

The gravitational force of objects with masses 1300012.67 kg 303213455.953 kg  of radius= 45.4 = 12.761610184592419

2)Calculating the Gravitational Force  (User Input)

Approach:

  • Scan the masses and radius as a floating data type and store in different variables
  • One of the variables should be set to the value of the gravitational constant, G.
  • The formula is used to calculate the force between the masses.
  • Print the force value, rounded up to two decimal places.
  • Exit the program.

Below is the implementation:

# scanning  first mass as float
mass1 = float(input("Enter the first mass of the object ="))
# given second mass as float
mass2 = float(input("Enter the second mass of the object ="))
# enter the radius as float
radius = float(input("Enter the distance/radius between the objects ="))
# Given value of Gravitational Constant Gval
Gval = 6.673*(10**(-11))
# Calculating the value of the gravitational force Gforce
Gforce = (Gval*mass1*mass2)/(radius**2)
# printing the value of gravitational force
print("The gravitational force of objects with masses", str(mass1) +
      " kg "+str(mass2)+" kg ", "of radius=", radius, "=", Gforce)

Output:

Enter the first mass of the object =2491855.892
Enter the second mass of the object =9000872
Enter the distance/radius between the objects =50
The gravitational force of objects with masses 24918552.892 kg 23145689000872.0 kg of radius= 50.0 = 15394799.86164859

Related Programs:

Python Program to Check Whether given Array or List Can Form Arithmetic Progression

Python Program to Check Whether given Array or List Can Form Arithmetic Progression

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

Arithmetic Progression:

Arithmetic Progression (AP) is a numerical series in which the difference between any two consecutive numbers is a constant value. For instance, the natural number sequence: 1, 2, 3, 4, 5, 6,… is an AP with a common difference between two successive terms (say, 1 and 2) equal to 1. (2 -1). Even when dealing with odd and even numbers, we can observe that the common difference between two sequential terms is equal to 2.

Examples:

Example1:

Input:

Given List = [9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69]

Output:

The given list [9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69] is in AP

Example2:

Input:

Given List = [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99, 105]

Output:

The given list [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99, 105] is in AP

Python Program to Check Whether given Array or List Can Form Arithmetic Progression

Below are the ways to Check Whether the given array or list can form the Arithmetic Progression series.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Create a function checkAp() which returns true if the given list is in Arithmetic Progression Else it returns False.
  • Pass the given list as an argument to the checkAp() function.
  • Calculate the length of the given list using the length() function.
  • Inside the Function sort the given list using the built-in sort() function.
  • Now compute the difference between the first two elements of the given list and initialize a new variable commondif with this difference.
  • Traverse the array in reverse order i.e from n-1 to 1 index using For loop.
  • Compare the difference between successive elements.
  • If the difference is not equal to commondif then return False.
  • After the end of For loop return True (This signifies that the given list is in Ap)
  • The Exit of the Program.

Below is the implementation:

# Create a function checkAp() which returns true if the given list
# is in Arithmetic Progression Else it returns False.


def checkAp(gvnlst):
  # Calculate the length of the given list using the length() function.
    lstlen = len(gvnlst)
    # Inside the Function sort the given list using the built-in sort() function.
    gvnlst.sort()
    # Now compute the difference between the first two elements of the given list and
    # initialize a new variable commondif with this difference.
    commondif = gvnlst[1]-gvnlst[0]
    # Traverse the array in reverse order i.e from n-1 to 1 index using For loop.
    for m in range(lstlen-1, 1, -1):
      # Compare the difference between successive elements.

        if(gvnlst[m]-gvnlst[m-1] != commondif):
          # If the difference is not equal to commondif then return False.
            return 0
    # After the end of For loop return True (This signifies that the given list is in Ap)
    return 1


# Give the list as static input and store it in a variable.
givenlist = [9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69]
# Pass the given list as an argument to the checkAp() function.
if(checkAp(givenlist)):
    print('The given list', givenlist, 'is in AP')
else:
    print('The given list', givenlist, 'is not in AP')

Output:

The given list [9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69] is in AP

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Create a function checkAp() which returns true if the given list is in Arithmetic Progression Else it returns False.
  • Pass the given list as an argument to the checkAp() function.
  • Calculate the length of the given list using the length() function.
  • Inside the Function sort the given list using the built-in sort() function.
  • Now compute the difference between the first two elements of the given list and initialize a new variable commondif with this difference.
  • Traverse the array in reverse order i.e from n-1 to 1 index using For loop.
  • Compare the difference between successive elements.
  • If the difference is not equal to commondif then return False.
  • After the end of For loop return True (This signifies that the given list is in Ap)
  • The Exit of the Program.

Below is the implementation:

# Create a function checkAp() which returns true if the given list
# is in Arithmetic Progression Else it returns False.


def checkAp(gvnlst):
  # Calculate the length of the given list using the length() function.
    lstlen = len(gvnlst)
    # Inside the Function sort the given list using the built-in sort() function.
    gvnlst.sort()
    # Now compute the difference between the first two elements of the given list and
    # initialize a new variable commondif with this difference.
    commondif = gvnlst[1]-gvnlst[0]
    # Traverse the array in reverse order i.e from n-1 to 1 index using For loop.
    for m in range(lstlen-1, 1, -1):
      # Compare the difference between successive elements.

        if(gvnlst[m]-gvnlst[m-1] != commondif):
          # If the difference is not equal to commondif then return False.
            return 0
    # After the end of For loop return True (This signifies that the given list is in Ap)
    return 1


# Give the list as user input using list(),map(),input(),and split() functions.
# store it in a variable.
givenlist = list(
    map(int, input('Enter some random List Elements separated by spaces = ').split()))
# Pass the given list as an argument to the checkAp() function.
if(checkAp(givenlist)):
    print('The given list', givenlist, 'is in AP')
else:
    print('The given list', givenlist, 'is not in AP')

Output:

Enter some random List Elements separated by spaces = 3 9 15 21 27 33 39 45 51 57 63 69 75 81 87 93 99 105
The given list [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99, 105] is in AP

Related Programs:

Python Program for Triangular Matchstick Number

Program for Triangular Matchstick Number

In the previous article, we have discussed Python Program for Maximum Number of Squares that Can Fit in a Right Angle Isosceles Triangle
Given a number x, which is the floor of the matchstick pyramid and the task is to find the number of matchsticks needed to form a pyramid of matchsticks of x floors.

Formula:

(3*x*(x+1))/2

Examples:

Example1:

Input:

Given number of floors = 3

Output:

The Number of matchsticks needed to form a pyramid of matchsticks :
18

Example2:

Input:

Given number of floors = 5

Output:

The Number of matchsticks needed to form a pyramid of matchsticks :
45

Program for Triangular Matchstick Number in Python

Below are the ways to find the number of matchsticks needed to form a pyramid of matchsticks of x floors:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Create a function to say count_MatchSticks() which takes the given number as an argument and returns the count of the number of matchsticks needed to form a pyramid of matchsticks for a given number of floors.
  • Inside the function, calculate the number of matchsticks needed using the above given mathematical formula and store it in a variable.
  • Return the above result.
  • Pass the given number as an argument to the count_MatchSticks() function, convert it into an integer using the int() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say count_MatchSticks() which takes the given number as an
# argument and returns the count of the number of matchsticks needed to form a
# pyramid of matchsticks for a given number of floors.


def count_MatchSticks(no_floors):
    # Inside the function, calculate the number of matchsticks needed using the above
    # given mathematical formula and store it in a variable.
    no_sticks = (3 * no_floors * (no_floors + 1)) / 2
    # Return the above result.
    return no_sticks


# Give the number as static input and store it in a variable.
no_floors = 3
print("The Number of matchsticks needed to form a pyramid of matchsticks :")
# Pass the given number as an argument to the count_MatchSticks() function, convert
# it into an integer using the int() function and print it.
print(int(count_MatchSticks(no_floors)))

Output:

The Number of matchsticks needed to form a pyramid of matchsticks :
18

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Create a function to say count_MatchSticks() which takes the given number as an argument and returns the count of the number of matchsticks needed to form a pyramid of matchsticks for a given number of floors.
  • Inside the function, calculate the number of matchsticks needed using the above given mathematical formula and store it in a variable.
  • Return the above result.
  • Pass the given number as an argument to the count_MatchSticks() function, convert it into an integer using the int() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say count_MatchSticks() which takes the given number as an
# argument and returns the count of the number of matchsticks needed to form a
# pyramid of matchsticks for a given number of floors.


def count_MatchSticks(no_floors):
    # Inside the function, calculate the number of matchsticks needed using the above
    # given mathematical formula and store it in a variable.
    no_sticks = (3 * no_floors * (no_floors + 1)) / 2
    # Return the above result.
    return no_sticks


# Give the number as user input using the int(input()) function and store it in a variable.
no_floors = int(input("Enter some random number = "))
print("The Number of matchsticks needed to form a pyramid of matchsticks :")
# Pass the given number as an argument to the count_MatchSticks() function, convert
# it into an integer using the int() function and print it.
print(int(count_MatchSticks(no_floors)))

Output:

Enter some random number = 5
The Number of matchsticks needed to form a pyramid of matchsticks :
45

Remediate your knowledge gap by attempting the Python Code Examples regularly and understand the areas of need and work on them.